Angular6父子元件的傳值問題總結
阿新 • • 發佈:2018-12-21
一.父元件向子元件傳資料
<!-- 將userName的值通過[name]屬性傳給子元件 -->
<!-- 父元件html -->
<app-father [name]='userName'></app-father>
//父元件ts
//要傳的資料userName
userName = 'user1';
//子元件ts
import { Component,OnInit,Input, Output, EventEmitter} from '@angular/core';
@Component({
selector: 'app-child' ,
templateUrl: './app-child.component.html'
})
export class AppChildComponent implements OnInit {
@Input() name:string;
ngOnInit() {
console.log(this.name) //'user1'
}
}
二.子元件向父元件傳資料
<!-- 子元件html -->
<!-- 子元件傳送資料的觸發方法 -->
<button (click)="emitNewName()">傳送</button >
//子元件ts
import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-child',
templateUrl: './app-child.component.html'
})
export class AppChildComponent implements OnInit {
@Output() onNameChanged = new EventEmitter();
newName = 'newName';
ngOnInit () {
}
emitNewName() {
this.onNameChanged.emit(this.newName);
}
}
<!-- 父元件html -->
<app-father (onNameChanged)='nameChanged($event)'></app-father >
//父元件ts
nameChanged(newName){
console.log(newName); //'newName'
}
三.父元件獲取子元件屬性或方法
方法一 (子元件加上屬性標記,只能在html中使用,ts中無效).
//子元件ts 定義子元件屬性newName 和方法getName()
newName = 'newName';
getName(){
console.log('get it',this.newName);
}
<!-- 父元件html 訪問子元件屬性和方法 -->
<app-child #child></app-child>
{{child.newName}}
<button (click)="child.getName()">點選</button>
方法二.(使用@ViewChild)
//父元件ts
import { Component, OnInit, ViewChild} from '@angular/core';
//引入子元件
import { AppChildComponent } from './components/app-child/app-child.component';
export class AppFatherComponent implements OnInit {
@ViewChild(AppChildComponent)
child:AppChildComponent
ngOnInit() {
console.log(this.child.newName)
}
}
方法三.
//父元件ts
//引入子元件
import { AppChildComponent } from './components/app-child/app-child.component';
export class AppFatherComponent implements OnInit {
constructor(private appChildComponent :AppChildComponent )
ngOnInit() {
console.log(this.appChildComponent.newName)
}
}
//父元件app.father.module.ts import子元件
@NgModule({
declarations: [
AppFatherComponent,
AppChildComponent
],
imports: [
AppChildComponent // ************需要匯入
]
})