天天看點

angular8 父子元件傳值

這裡講解angular8版本的一些項目上常用到的知識點

1、父子元件如何進行通信

利用@Input()和@Output()兩個裝飾器(注解)進行通信

子元件傳值給父元件

子元件test.component.ts

import { Component, OnInit, Output, EventEmitter } from '@angular/core';

@Component({

  selector: 'test'

  templateUrl: './test.cmponent.html',

  styleUrls: ['./test.component.scss']

})

export class TestComponent implements OnInit {

  @Output() taskData = new EventEmitter;

  constructor() {

  }

  ngOnInit() {

      this.taskData.emit("我是在子元件中擷取到的值,需要傳給父元件");

  }

}

父元件html

<div>

    <test (taskData)="getTaskData($event)"></test>// /子元件1

    <test2></test2>// /子元件2

</div>

父元件ts

import { Component, OnInit } from '@angular/core';

@Component({

  selector: 'test',

  templateUrl: './test.component.html',

  styleUrls: ['./test.component.scss']

})

export class InvestmentProfileComponent implements OnInit {

  public taskData;

  constructor() { 

  }

  ngOnInit() {

  }

  public getTaskData($event) {

    this.taskData = $event;    // $even就是擷取到子元件傳過來的值,并把值存入變量taskData 

  }

}

父元件傳值給子元件

父元件html

<div>

    <test (taskData)="getTaskData($event)"></test>// /子元件1

    <test2 [taskData]="taskData"></test2>// /子元件2

</div>

子元件ts

import { Component, OnInit, Output, EventEmitter } from '@angular/core';

@Component({

  selector: 'test'

  templateUrl: './test.cmponent.html',

  styleUrls: ['./test.component.scss']

})

export class TestComponent implements OnInit {

  @Input () taskData //接受父元件傳來的值

  constructor() {

  }

  ngOnInit() {

  }

}