【问题标题】:Angular @Input pass data from index htmlAngular @Input 从索引 html 传递数据
【发布时间】:2019-09-02 10:28:08
【问题描述】:

我正在尝试使用来自 HTML 页面的 @Input 接收数据。

示例 - 根组件

Template : "<div><comp1 value='hello'</div>"
Selector : "app-root"

子组件

Template : "<input type='text' [value]='value'/>"
Selector : "comp1"

class{
@Input value:string;
}

index.html

<body>
<app-root></<app-root>
</body>

尝试 1: 结果:子组件显示 hello

尝试 2: index.html

<body>
<comp1 value='test'></comp1>
</body>

引导更改为 ChildComponent

结果:子组件值什么都不显示。

子 ts 文件

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


@Component({
  selector: 'app-arc-chart',
  templateUrl: './arc-chart.component.html',
  styleUrls: ['./arc-chart.component.css'],
  encapsulation: ViewEncapsulation.Emulated
})
export class ArcChartComponent implements OnInit {

  @Input() textValue:string = "123";

  constructor() {

  }

  ngOnInit() {
    debugger;
    console.log(this.textValue);
  }

}

child html file
<input type="text" value="{{textValue}}" />

应用 ts 文件

 import {
      Component
    } from "@angular/core";


        @Component({
          selector: "app-root",
          templateUrl: "./app.component.html",
          styleUrls: ["./app.component.css"]
        })
        export class AppComponent implements OnInit {
          }

应用程序 html 文件

<div>
<app-arc-chart textValue="555"></app-arc-chart>
</div>

如果我更改 Index.html 中的属性值,我期待值更改。 &lt;app-arc-chart textValue='hahaha'&gt;&lt;/app-arc-chart'&gt;

【问题讨论】:

    标签: angular input


    【解决方案1】:

    您必须像我在下面的代码中所做的那样,用“[]”将@Input 括起来。

    <div>
    <app-arc-chart [textValue]="555"></app-arc-chart>
    </div>
    

    谢谢。

    【讨论】:

    • 感谢 Ronak,我在没有用括号括起来之前尝试过它在 appcomponent.html 中的工作。我真正想做的是,如果我在 index.html 中为选择器属性更改任何内容,它将反映值的更改。
    • @Issac,你能给我任何像 StackBlitz 这样的在线角度编辑器的链接吗?所以它对我有用。谢谢。
    • 嗨 Ronak,我想我已经通过创建自定义元素解决了这个问题。感谢您的快速回复。
    【解决方案2】:

    index.html 只是一个简单的 HTML 文件。它不与任何组件相关联。因此,您不能在其中编写 Angular 选择器或任何其他角度逻辑。

    当应用程序启动时,它会引导 AppComponent(或在 app.module 中添加为 bootstrap: [AppComponent] 的任何其他组件,

    你应该只有

    <body>
      <app-root></app-root>
    </body>
    

    在 index.html 中。其他一切都应该在一个组件中。

    【讨论】:

    • 嗨,Adrita 感谢您的快速响应,我们可以在 index.html 中做一些事情,可以通过像角度 @Input 这样的属性传递数据吗?我看到有人过去做过,但我没有源代码,所以不知道他/她做了什么。所以当我使用那个 JS 的引用时,我可以简单地注入带有属性的选择器来通过属性传递值。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-07
    • 2018-04-24
    相关资源
    最近更新 更多