angular

angular--输入输出属性

2018-01-07  本文已影响0人  林ze宏

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

输入属性

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() {
  }

}

界面:
    <p>stock值:{{stock}}</p>
    <p>amount值:{{amount}}</p>


parent:在父组件通过属性绑定,把值传递到子组件。
<app-test-demo [stock]="title" [amount]="100" ></app-test-demo>

输出属性

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<Myprice> = new EventEmitter(); // EventEmitter需要指定类型

  @Output()
  myss: EventEmitter<number> = 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,是从子组件传递过来的值,父组件通过一个方法接收这个值
<app-test-demo (myss) = "getValNum($event)"></app-test-demo>
<div>数字:{{n | number:'2.2-2'}}</div>

<app-test-demo (lastPrice) = "getVal($event)"></app-test-demo>
<div>对象:{{ss.price | number:'2.2-2'}}</div>

ts:
import { Component } from '@angular/core';
import * as $ from '_jquery@3.2.1@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;
  }
  
}

image.png
上一篇下一篇

猜你喜欢

热点阅读