顾名思义,父组件定义数据或方法,子组件可以拿到。使用 Input可以实现:
首先在父组件中定义数据,如:
public msg:string='我来自父组件'
接着给组件绑定:
<p>this is father!p>
<app-son [msg]="msg">app-son>
之后在子组件中引入Input,然后使用@Input装饰器拿到传过来的数据:
import { Component, OnInit,Input } from '@angular/core';
@Component({
selector: 'app-son',
templateUrl: './son.component.html',
styleUrls: ['./son.component.css']
})
export class SonComponent implements OnInit {
public num:number=1;
@Input() msg:any;
constructor() { }
get(){
console.log(this.num);
}
ngOnInit(): void {
console.log(this.msg)
}
}
然后子组件就可以使用父组件的值了:
<p>this is son!p>
<p>{{msg}}p>
子组件定义数据或方法,父组件可以利用ViewChild获取到子组件进而拿到子组件传过来的数据方法,下面的例子是father组件使用son组件的get方法获取son里边的数据:
father组件:
<p>this is father!p>
<app-son #son>app-son>
import { Component, OnInit,ViewChild } from '@angular/core';
@Component({
selector: 'app-father',
templateUrl: './father.component.html',
styleUrls: ['./father.component.css']
})
export class FatherComponent implements OnInit {
@ViewChild('son') son:any;
constructor() { }
ngOnInit(): void {
}
ngAfterViewInit():void{
this.son.get();
}
}
son组件:
<p>this is son!p>
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-son',
templateUrl: './son.component.html',
styleUrls: ['./son.component.css']
})
export class SonComponent implements OnInit {
public num:number=1;
constructor() { }
get(){
console.log(this.num);
}
ngOnInit(): void {
}
}
控制台:
除此之外,还可以使用Outer,EventEmitter来达到目的,步骤:
在子组件中引入Outer,EventEmitter,并将EventEmitter的实例用@Outer导出,然后在子组件中定义要传数据和触发事件,当触发这个事件方法后,子组件会将数据广播出去:
import { Component, OnInit,Output,EventEmitter } from '@angular/core';
@Component({
selector: 'app-son',
templateUrl: './son.component.html',
styleUrls: ['./son.component.css']
})
export class SonComponent implements OnInit {
public num:number=123462681;
@Output() outer=new EventEmitter();
constructor() { }
ngOnInit(): void {
}
tofather(){
this.outer.emit(this.num)
}
}
<p>this is son!p>
<button (click)="tofather()">点击按钮传递数据给父组件button>
然后在父组件中的子组件标签上监听广播事件,触发父组件的方法,从这里拿到传过来的数据:
<p>this is father!p>
<app-son (outer)="get($event)">app-son>
get(e:any){
console.log(e);
}
使用service达到非组件的目的,可以参考https://editor.csdn.net/md/?articleId=126004856