在 Angular 的 []
中使用变量/表达式的范围是多少?在以下 Plunkr 代码中,helloWorld
在 rio-app
中定义,但在 rio-hello
中使用。 Angular 会一直搜索到根父级来查找变量吗?如果子组件和父组件具有相同的变量会发生什么?我在 hello.component.ts
中添加了 helloName: string = "test";
但输出不是 Hello test
http://plnkr.co/edit/LEtEN9?p=preview
<div>
<rio-hello name="World"></rio-hello>
<rio-hello [name]="helloName"></rio-hello>
</div>
更改了 hello.component.ts
但仍然得到相同的输出。
import { Component, Input } from '@angular/core';
@Component({
selector: 'rio-hello',
template: '<p>Hello, {{name}}!</p>',
})
export class HelloComponent {
@Input() name: string;
helloName: string = "test";
}
最佳答案
我猜rio-app
包含两个 rio-hello
?
如果是这样,它的工作原理如下:
首先,在 app
组件,您有一个名为 helloName
的变量。
在相应的 HTML 中,您会看到 2 hello
组件:
<rio-hello name="World"></rio-hello>
<rio-hello [name]="helloName"></rio-hello>
然后,在 hello
组件,你有这个:
@Input() name: string;
这行内容是
On the HTML selector of my component, there is an attribute called name. Please take its value and return it to me.
发生的事情是你的hello
组件将获取属性的值,并将其设置在变量中。但它如何决定采取什么?因为我们看到两个组件都有 name
属性,但写法不一样。
这与Angular 模板语法有关:简单来说,如下所示:
-
name="x"
:您将等于“x”的字符串发送到子组件 -
[name]="x"
:您将一个名为 x 的变量发送到您的组件,其中包含任何内容 -
(name)="x($event)"
:您的子组件向其父组件发送一个值,该父组件正在调用函数x
-
[(name)]="x"
:父级向子级发送一个 x 变量,该变量可以更新父级中 x 的值(需要更多代码)
我认为这应该解释它是如何工作的。但如果没有,请随时询问!
关于angular - 这个 Plunkr 代码是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47810317/