如何将数据从模板发送到Angular中包含的组件?



这是一个示例组件:

import { Component, Input, OnInit } from '@angular/core';
@Component({
selector: 'app-test',
templateUrl: './test.component.html',
styleUrls: ['./test.component.scss']
})
export class TestComponent implements OnInit {
@Input()
setTestVar: string = '';
testVar: string = '';
constructor() { }
ngOnInit(): void {
this.testVar = this.setTestVar;
}
}

你可以在另一个组件模板中这样使用:

...
<app-test [setTestVar]="variable_from_calling_component"></app-test>
...

但是我如何设置一个在调用组件中不作为变量存在的值呢?如何使用刚刚在调用模板中定义的值?

...
<app-test [setTestVar]="some_value"></app-test> /** does not work **/
...

组件的输入需要一个字符串。如果你在angular中使用[]括号,它需要一个存在于typescript文件中的方法名或变量。如果你想传递一个新的字符串,那么使用:

<app-test [setTestVar]="'some_value'"></app-test>

也可以使用:

<app-test setTestVar="some_value"></app-test>

最新更新