在阅读@Input()
和@Output()
时,我发现我们可以使用别名而不是使用装饰器的属性名称。
示例
class ProductImage {
//Aliased
@Input('myProduct') product: string;
//Un-aliased
@Input() product: string;//not aliased
}
HTML
//Aliased attribute
<SomeComponent [myProduct] = "Product Name"></SomeComponent>
//Un-aliased attribute
<SomeComponent [product] = "Product Name"></SomeComponent>
官方Angular documentation说:
有时我们希望输入/输出属性的公共名称与内部名称不同。 属性指令经常出现这种情况。指令消费者期望绑定到指令的名称。例如,当我们将带有myClick选择器的指令应用于标记时,我们希望绑定到也称为myClick的事件属性。
This教程简要解释了它:
别名让我将属性名称覆盖为别名而不是原始属性名称
除此之外,我无法在SO上或通过Google找到别名@Input()
和@Output()
上的任何内容。
我想知道的事情:
答案 0 :(得分:6)
这就像你的名字和你的昵称。
在你的家庭中,你可能被称为Nic,在家庭之外,为了让其他人合法地认识你,你应该被称为尼古拉斯。
所以,如果我们考虑你的组件的类,你的家庭内部:
@Component({
selector:'my-component'
})
export class MyComponent{
@Output('nicolas') nic = new EventEmitter<any>();
someFunction(){
// because we're inside the family ( inside this class ), instead of nicolas , we can call nic like this :
this.nic ...... ( which you'd normally emit an event ).
}
}
但是从外面来看,你仍然是尼古拉斯,所以当有人想要给你打电话时(使用那个事件发射器)它应该使用尼古拉斯;
<my-component (nicolas)="onNicolasChanged($event)"></my-component>
请注意,我们无法执行此操作:
<my-component (nic)="onNicolasChanged($event)"></my-component>
这是变量的别名。
另外,请阅读我的回答here:
答案 1 :(得分:2)
实际上,当我们将父组件的数据发送到子组件时使用@Input,而@Output则反之亦然。例子是
<p> Child first name is {{childfirstname}}</p>
<input placeholder="First Name" type="text" [(ngModel)]="firstname">
<button mat-button (click)="send()">Click Parent</button>
<app-child
[firstname]="firstname"
(sendfirstname)="reciveFirstname($event)"
*ngIf="flage">
<app-child>
import { Component } from '@angular/core';
@Component({
selector:.......
)}
export class ParentComponent {
flage: boolean = false;
firstname: string;
childfirstname: string;
}
send() {
this.flage = true;
}
reciveFirstname(firstname) {
this.childfirstname = firstname;
}
<p> Parent first name is {{firstname}} <br>
parent last name is {{lastname}} </p>
<input placeholder="First Name" type="text" [(ngModel)]="firstnamechild">
<button mat-button (click)="send">Send Parent</button>
import { Component,Input, Output, EventEmitter } from '@angular/core';
@Component({
selector:'app-child',
........
})
export class ChildComponent {
firstnamechild: string;
@Input() firstname: string;
@Output()
sendfirstname: EventEmitter<string> = new EventEmitter<string>();
constructor() {}
send() {
this.sendfirstname.emit(this.firstnamechild);
}
}
答案 2 :(得分:1)
它只是根据您的需要重命名输入/输出变量。例如,如果存在hero
对象,并且在选择它时将其传递给另一个组件。在这种情况下,称之为selectedHero
是合适的。别名只是实现了这一点。
@Input('selectedHero') hero: string;
取决于您正在处理的上下文。它不是必需品。例如,它可用于避免变量名称冲突或代码的可读性。
答案 3 :(得分:0)
使用它的一个很好的理由是,如果您需要更改组件中的变量名称,则无需在模板中更改它,因为它使用的是别名。如果另一个dev改变了变量名,这是一种防止代码破坏的简单方法。