Angular @Input从索引 html 传递数据



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

例- 根组件

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

子组件

Template : "<input type='text' [value]='value'/>"
Selector : "comp1"
class{
@Input value:string;
}

索引.html

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

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

尝试 2: 索引.html

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

引导程序更改为子组件

结果:子组件值不显示任何内容。

子 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 中的属性值,我希望值会发生变化。<app-arc-chart textValue='hahaha'></app-arc-chart'>

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

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

谢谢。

索引.html只是一个简单的HTML文件。它不与任何组件关联。所以你不能在其中写角度选择器或任何其他角度逻辑。

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

你应该只有

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

在索引中.html。其他所有内容都应在组件中。

最新更新