1、父组件的代码
// parent.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-parent',
templateUrl: './parent.component.html',
styleUrls: ['./parent.component.styl']
})
export class ParentComponent implements OnInit {
public inputData = 'inputTest';
constructor() { }
ngOnInit(): void {
}
}
// parent.component.html
<p>
<app-child [inputData]="inputData"></app-child>
</p>
2、子组件的代码
<1>、第一种接收方式,不便于对数据进行切面拦截,inputData可以作为属性在模板中直接使用。
// child.component.ts
import { Component, OnInit, Input } from '@angular/core';
@Component({
selector: 'app-child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.styl']
})
export class ChildComponent implements OnInit {
@Input()
public inputData: string;
constructor() { }
ngOnInit(): void {
}
}
// child.component.html
<p>输入的数据是:{{inputData}}</p>
<2>、第二种接收方式,方便于对数据进行切面拦截,inputData不能作为属性在模板中直接使用。
// child.component.ts
import { Component, OnInit, Input } from '@angular/core';
@Component({
selector: 'app-child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.styl']
})
export class ChildComponent implements OnInit {
public _inputData: string;
constructor() { }
ngOnInit(): void {
}
@Input() set inputData(data: string) {
// 对从父组件传入的数据进行拦截处理
const temp = data.toUpperCase();
// _inputData可以作为属性在模板中使用
this._inputData = temp;
}
}
// child.component.html
<p>输入的数据是:{{_inputData}}</p>
本文介绍了Angular中使用@Input装饰器从父组件向子组件传递数据的两种方法。第一种方式简单直接,数据可在模板中直接使用;第二种方式则有利于在数据传递过程中进行拦截处理,但无法直接在模板中使用输入数据。
2439

被折叠的 条评论
为什么被折叠?



