一、@ViewChild
父組件中使用@ViewChild拿到子組件的變量和方法(父組件可調用子組件的方法和變量)
parent.component.ts:
import { Component, OnInit, ViewChild } from '@angular/core';
import { ChildComponent } from './child.component';
@Component({
selector: 'my-parent',
templateUrl: './parent.component.html',
styleUrls: [ './parent.component.css' ],
})
export class ParentComponent implements OnInit {
//通過@ViewChild注冊子組件
@ViewChild(ChildComponent) public child:ChildComponent;
public countNum: number;
public firstName:string = "Jeck";
public fullName:string = "";
constructor() {}
ngOnInit(): void {
}
displayFull(){
this.fullName = this.firstName + this.child.lastName;
console.log(this.fullName) //"Jeck wang"
}
}
child.component.ts:
import { Component, OnInit} from '@angular/core';
@Component({
selector: 'my-child',
templateUrl: './child.component.html',
styleUrls: [ './child.component.css' ],
})
export class ChildComponent implements OnInit {
public lastName:string = "wang";
constructor() {}
ngOnInit(): void {
}
}
二、@Inject
子組件中使用@Inject調用父組件中的變量和方法
parent.component.ts:
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'my-parent',
templateUrl: './parent.component.html',
styleUrls: [ './parent.component.css' ],
})
export class ParentComponent implements OnInit {
constructor() {}
ngOnInit(): void {
}
sayHello(){
console.log("Hello!")
}
}
child.component.ts:
import { Component, OnInit, Inject, forwardRef} from '@angular/core';
import { ParentComponent } from './parent.component';
@Component({
selector: 'my-child',
templateUrl: './child.component.html',
styleUrls: [ './child.component.css' ],
})
export class ChildComponent implements OnInit {
constructor(
@Inject(forwardRef(()=>ParentComponent)) public parent:ParentComponent
) {}
ngOnInit(): void {
this.parent.sayHello(); //"Hello!"
}
}
注意:如果父子模塊通過以上方式相互引用,請在父模塊中使用 @ViewChild(forwardRef(()=>ChildComponent)) public child:ChildComponent 方式避免父子組件循環引用報錯
