angular--输入输出属性

有父子关系的两个组件:parent、child

  • @Input():输入属性,,在父组件通过属性绑定,传递数据到子组件(父=》子)
  • @Output():输出属性,在父组件通过绑定事件,把子组件中的数据传递到父组件(子=》父)

输入属性

child:
import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
import { Observable } from 'rxjs';
import { Data } from '@angular/router/src/config';
@Component({
  selector: 'app-test-demo',
  templateUrl: './test-demo.component.html',
  styleUrls: ['./test-demo.component.css']
})
export class TestDemoComponent implements OnInit {
  @Input()
  public stock: string;

  @Input()
  public amount: number;

  constructor() {
   }

  ngOnInit() {
  }

}

界面:
    

stock值:{{stock}}

amount值:{{amount}}

parent:在父组件通过属性绑定,把值传递到子组件。

输出属性

child:
import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
import { Observable } from 'rxjs';
import { Data } from '@angular/router/src/config';
@Component({
  selector: 'app-test-demo',
  templateUrl: './test-demo.component.html',
  styleUrls: ['./test-demo.component.css']
})
export class TestDemoComponent implements OnInit {

  @Output()
  lastPrice: EventEmitter = new EventEmitter(); // EventEmitter需要指定类型

  @Output()
  myss: EventEmitter = new EventEmitter();

  constructor() {
    setInterval(() => {
     let tt: Myprice = new Myprice("QQ", 100 * Math.random());
     let n: number = tt.price;

     this.lastPrice.emit(tt); // 通过EventEmitter 的 emit方法,向父组件传递一个对象

     this.myss.emit(n); // 向父组件传递通过值

    }, 1000);
   }

  ngOnInit() {
  }

}

export class Myprice { // 定义一个对象
  constructor(
    public stock: string,
    public price: number) { }
}

parent:
界面: (myss) = "getValNum($event)" 中 方法的参数$event,是从子组件传递过来的值,父组件通过一个方法接收这个值

数字:{{n | number:'2.2-2'}}
对象:{{ss.price | number:'2.2-2'}}
ts: import { Component } from '@angular/core'; import * as $ from '[email protected]@jquery'; import { Myprice } from './test-demo/test-demo.component'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { public ss: Myprice = new Myprice("", 0); public n: number; getVal(val: Myprice) { this.ss = val; } getValNum(val: number) { this.n = val; } }
angular--输入输出属性_第1张图片
image.png

你可能感兴趣的:(angular--输入输出属性)