【问题标题】:How to pass value to component from html?如何将值从html传递给组件?
【发布时间】:2020-07-05 15:53:32
【问题描述】:

我想将静态值从 html 传递给组件,但它不起作用,我整天都被卡住了......你能给我一些胶水吗?谢谢

组件:

import { Component, Input } from '@angular/core';

@Component({
  selector: 'rio-hello',
  template: `<p>Hello, {{name}}!</p>
    <button (click)="greet()">Show Greet</button>
  `,
})
export class HelloComponent {
  @Input()
  name: string;

  greet(){
    console.log(`Hello,${name}`);
  }
}

入口html index.html

<rio-hello name="World"></rio-hello>

我期待的是它可以在页面上打印Hello, World,并且可以在组件中将name属性设置为World,如何实现?

【问题讨论】:

    标签: angular


    【解决方案1】:

    您需要添加this 来引用name,因为它是您的HelloComponent 实例的一部分:

    greet() {
      console.log(`Hello, ${this.name}`);
    }
    

    您的模板看起来不错。

    编辑:由于您在引导组件中使用@Input,因此似乎不可能这样做:

    【讨论】:

    • 即使添加关键字 this 也不起作用。控制台显示 Hello,undefined ,页面显示 Hello,!, World just not got by component。
    • 您能否将&lt;rio-hello name="World"&gt;&lt;/rio-hello&gt; 添加到您的app.component.html 而不是index.html(其中&lt;app-root&gt;&lt;/app-root&gt; 应该在index.html 中)?
    • 是的,如果我将应用程序组件作为引导组件并在 app.component.html 中使用 rio-hello,那应该可以工作,但这不是我的确切期望,我希望给用户一个机会直接在第一个位置设置名称值,index.html 而不是父组件。我在stackblitz.com/edit/angular-ivy-gmzdeh 创建了一个实时 Angular 项目,每个人都可以在线编辑和运行它,也许你可以看看。感谢您的回答
    • 是否可以获得看起来非常有用的自举组件的属性?假设应用程序组件需要解析名称和路径配置在属性上的文件。如果无法直接获取路径,我们将无法解析它。似乎@input 仅适用于父子组件之间的数据传递
    猜你喜欢
    • 1970-01-01
    • 2017-12-08
    • 2020-02-04
    • 1970-01-01
    • 1970-01-01
    • 2019-09-09
    • 2021-10-22
    • 2020-05-07
    • 1970-01-01
    相关资源
    最近更新 更多