angular - 这个 Plunkr 代码是如何工作的?

标签 angular

在 Angular 的 [] 中使用变量/表达式的范围是多少?在以下 Plunkr 代码中,helloWorldrio-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/

相关文章:

angular - 找不到模块 : Error: Can't resolve './package' in Angular 6

html - 并排对齐div - Angular

javascript - 影子dom内的脚本不起作用

html - Angular:如何在纸牌游戏中重叠输入,具体取决于谁先出牌?

angular - 如何更改 ngfor 内各个元素的类?

node.js - 无法在 Ubuntu 中卸载 Angular CLI - 显示 `up to date in 0.083s`

angular - 将变量传递给 Angular 应用程序以使其成为全局变量

Angular 4 - 将事件转换为可观察的流

angular - 空注入(inject)器错误 : No provider for NgZone when referencing a custom npm package

javascript - 阅读单选按钮值 - Angular 2