gpt4 book ai didi

javascript - 可以从 Angular 4 组件模板属性调用函数吗?

转载 作者:行者123 更新时间:2023-12-03 03:11:08 25 4
gpt4 key购买 nike

我想知道是否可以从 Angular 4 组件的模板属性调用函数,如下所示?我希望从函数中以字符串形式返回模板,甚至可能返回模板 url。模板将根据 @Input 字符串值进行选择,并成为函数签名的一部分。

目前我收到“this.getTemplate 不是函数”

如有任何帮助,我们将不胜感激!

@Component({
selector: 'app-test',
styleUrls: ['./test.component.css'],
template: this.getTemplate(this.templateName)
})

export class TestComponent implements OnInit {

@Input() templateName: string = '';

getTemplate(name: string) : string {

if (name == "first") {
return `<h5>First Template</h5>`
}
return `<h5>Second Template</h5>`
}

getTemplate(name: string) : string {
if (name == "first") {
return './first.component.html'
} else {
return './second.component.html'
}
}

constructor() {}
ngOnInit() {}
}

最佳答案

,这是不可能的。您需要静态引用它,否则 Angular 将找不到要加载的模板。

因为 Angular 编译器需要首先找到模板并能够访问它。它无法解析变量或函数。

看看这个问题https://github.com/angular/angular/issues/14323

关于javascript - 可以从 Angular 4 组件模板属性调用函数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46944536/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com