angular 11 将静态文本显示为动态值
angular 11 display static text to dynamic value
我有 2 JSONs。第一个是 JSON 值的格式,第二个是我想在 UI.
中显示的实际值
但是我看到的是“application.appID”而不是 101。请问有什么帮助吗?
如果标签为:“applicaiton.appID”,则无效。我有标签:“string”
工作如果标签:applicaiton.appID
component.ts
this.json1={
label:"applicaiton.appID"
};
this.application ={
appID:101
};
ui.html
<mat-label> {{json1.label}} </mat-label>
<mat-label [innterHtml]="json1.lable"> </mat-label>
如果我没理解错的话,您要做的是根据来自 json 的字符串表达式进行插值。这不是仅使用 {{ }} 构造就可以完成的事情。原因如下:
(为简单起见,我将使用 div 而不是 mat-label)
理论上,这条线可以解决你的问题
<div>{{this[json1.label]}}</div>
只是它不起作用,因为内部 json1.label
部分不是预期的 expanded/evaluated。
即使我们手动将其写为显式字符串,它仍然不会给我们101
。
<div>{{this['application.appID']}}</div>
使这种语法起作用的唯一方法是链接字段索引器,但这对我们使用 json1.label 作为对象和内部字段的 'path' 没有帮助。
<div>{{this['application']['appID']}}</div> // this returns 101, but it's not helpful for us...
因此,如您所见,纯 html 插值并不能真正帮助我们实现目标。相反,我们应该在 .component.ts 文件中创建一个辅助方法:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
json1 = {
label: 'application.appID'
};
application = {
appID: 101
};
accessPropertyByString(path: string): any {
let result = this;
const parts = path.split('.');
for (const part of parts) {
if (part in result) {
result = result[part];
} else {
return null;
}
}
return result;
}
}
新的 accessPropertyByString()
方法现在可以像这样在 html 模板中使用:
<div>{{accessPropertyByString(json1.label)}}</div>
最终 returns 101
符合预期。
我有 2 JSONs。第一个是 JSON 值的格式,第二个是我想在 UI.
中显示的实际值但是我看到的是“application.appID”而不是 101。请问有什么帮助吗?
如果标签为:“applicaiton.appID”,则无效。我有标签:“string”
工作如果标签:applicaiton.appID
component.ts
this.json1={
label:"applicaiton.appID"
};
this.application ={
appID:101
};
ui.html
<mat-label> {{json1.label}} </mat-label>
<mat-label [innterHtml]="json1.lable"> </mat-label>
如果我没理解错的话,您要做的是根据来自 json 的字符串表达式进行插值。这不是仅使用 {{ }} 构造就可以完成的事情。原因如下:
(为简单起见,我将使用 div 而不是 mat-label)
理论上,这条线可以解决你的问题
<div>{{this[json1.label]}}</div>
只是它不起作用,因为内部 json1.label
部分不是预期的 expanded/evaluated。
即使我们手动将其写为显式字符串,它仍然不会给我们101
。
<div>{{this['application.appID']}}</div>
使这种语法起作用的唯一方法是链接字段索引器,但这对我们使用 json1.label 作为对象和内部字段的 'path' 没有帮助。
<div>{{this['application']['appID']}}</div> // this returns 101, but it's not helpful for us...
因此,如您所见,纯 html 插值并不能真正帮助我们实现目标。相反,我们应该在 .component.ts 文件中创建一个辅助方法:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
json1 = {
label: 'application.appID'
};
application = {
appID: 101
};
accessPropertyByString(path: string): any {
let result = this;
const parts = path.split('.');
for (const part of parts) {
if (part in result) {
result = result[part];
} else {
return null;
}
}
return result;
}
}
新的 accessPropertyByString()
方法现在可以像这样在 html 模板中使用:
<div>{{accessPropertyByString(json1.label)}}</div>
最终 returns 101
符合预期。