使用 Angular 中的输入进行组件交互

输入提供了一种机制,允许父组件绑定子组件可以访问的属性。父零部件将特性推送到子零部件。

<$>[note]这篇文章涵盖了Angular 2和更高版本<$>

在父组件的模板中,只需在子组件的选择器中定义属性绑定。绑定应该指向父组件类中等号右侧的可用属性,您希望子组件可以使用这些属性。至于绑定本身的名称(等号的左侧),这完全取决于您:

1[label Parent component template: story.component.html]
2<selected-story [story]="currentStory" [character]="mainCharacter">
3</selected-story>
1[label Parent component class: story.component.ts]
2export class StoryComponent {
3  currentStory: string = 'The Fox Without a Tail';
4  mainCharacter: string = 'Henry';
5}

现在,在子组件中,从@Angel/code导入输入,并使用@Input修饰符定义您的输入,如下所示:

1[label Child component class: selected-story.component.ts]
2import { Component, Input } from '@angular/core';
3
4//...

我们的子组件现在可以从父组件访问CurrentStory和mainCharacter的值。请注意,我们如何为角色设置别名,以调用子组件中的属性myCharacter:

1[label Child component template: selected-story.component.html]
2The story: {{ story }}
3The character: {{ myCharacter }}

♪然后请参阅:

Published At
Categories with 技术
Tagged with
comments powered by Disqus