如何在Angular中检测@Input()值的变化
@Input()
基本上是一个装饰器,用来绑定一个属性作为输入。它被用来传递数据,即从一个组件到另一个组件的属性绑定,或者我们可以说,从父组件到子组件。它是与DOM元素绑定的。当DOM元素的值发生变化时,Angular会自动用变化的值更新这个属性。在这里,我们将看到我们如何使用它。
方法: @Input()
可以以两种方式使用。
- 用@Input()进行双向绑定
- 用ngOnChange()和@Input()进行单向绑定
-
首先,我们将看一下双向绑定。
双向绑定使用ngModel指令将输入和输出结合在一个单一的符号中。双向绑定的符号是[()]
。
下面是我们将如何实现双向绑定。我们有一个组件FormComponent(父母)和ChildComponent(孩子)。当用户在父组件的文本输入框中输入任何东西时,子组件会检测到它。
Implementation of Two-way binding:
在这里,我们正在创建一个父组件,并向其添加子组件。
form.component.html
<div style="border: 1px solid rgb(46, 93, 194);
height: 25vh;
width: 35vw;
padding: 10px 10px;
margin: 20px;" >
<b>Type here : </b>
<input type="text" [(ngModel)]='text' />
<child [message]='text'></child>
</div>
在子组件中,我们要传递一个属性’message’,它持有输入元素使用ngModel绑定的值。这里是FormComponent类。
form.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-form',
templateUrl: './form.component.html',
styleUrls: ['./form.component.scss']
})
export class FormComponent implements OnInit {
constructor() { }
ngOnInit(): void {
}
public text : string;
}
这一变化将反映在子组件中。消息 “将显示在这里。以下是相关的代码。
child.component.html
<div style="border:1px solid rgb(53, 71, 131);
width:30vw;
height: 12vh;
padding: 10px 10px;
margin:20px">
<h4> You entered <span>{{message}}</span></h4>
</div>
在ChildComponent类中,我们将导入Input,以便从FormComponent类中检测信息。
child.component.ts
import { Component, OnInit, Input } from '@angular/core';
@Component({
selector: 'child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.scss']
})
export class ChildComponent {
//message will detect the input from FormComponent.
@Input() message:string;
constructor() { }
}
这都是关于双向绑定的。现在我们来看看如何使用单向绑定。
*
Implementation of One-way binding with ngOnChange() and @Input():
下面是我们如何使用ngOnChange()来绑定输入。childComponent的代码将与双向绑定的情况相同。然而,FormComponent将有onChange()方法被调用。下面是相关的代码。
form.component.html
<div style="border: 1px solid rgb(46, 93, 194);
height: 25vh;
width: 35vw;
padding: 10px 10px;
margin: 20px;" >
<b>Type here : </b>
<input type="text"
[ngModel]='text'
(ngModelChange)='onChange($event)' />
<child [message]='text'></child>
</div>
注意这个组件和之前的代码的区别,它显示了双向绑定。这里,ngModel和ngModelChange都与输入元素绑定。由于我们使用了onChange(),我们不需要使用@Input()来检测变化。
form.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-form',
templateUrl: './form.component.html',
styleUrls: ['./form.component.scss']
})
export class FormComponent implements OnInit {
constructor() { }
ngOnInit(): void {
}
public text : string;
onChange(UpdatedValue : string) :void
{
this.text = UpdatedValue;
}
}