1. 程式人生 > >angular父子元件傳值

angular父子元件傳值

angular 元件傳值---****---子傳父。。。。@Output
*****子元件
--------ts檔案
import {Component, Output, EventEmitter,OnInit} from '@angular/core';
@Component({
selector: 'child-Component',
templateUrl: './child.component.html',
styleUrls: ['./child.component.less']
})
export class childComponent implements OnInit {
//使用"事件傳遞"是 "子元件" 向 "父元件" 傳遞資料最常用的方式,子元件需要例項化EventEmitter類來訂閱和觸發自定義事件
@Output() childDataevent = new EventEmitter();//自定義事件 例項化EventEmitter,賦值給event,event被@Output裝飾器定義為輸出屬性,
private username: string; // 這樣event具備了向上級傳遞資料的能力,通過呼叫EventEmitter類中定義的emit方法,來向上傳遞資料

constructor() {}
ngOnInit(): void {}
submitVal(){
this.childDataevent.emit(this.username);
return
}
}
-----html檔案
使用者名稱<input nz-input [(ngModel)]="username" name="username" type="text">
<button (click)="submitVal()">提交--子傳父</button>
*****父元件
--------ts檔案
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'logoSing',
templateUrl: './logoSing.html',
styleUrls: ['./logoSing.css']
})
export class LogoSingComponent implements OnInit {
private parent_username: string;
constructor() { }
ngOnInit() { }
getData(event) {
this.parent_username = event;
}
}
--------html檔案
子元件展示在父元件的值:{{parent_username}}
<child-Component (childDataevent)="getData($event)"></child-Component>