Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
876 views
in Technique[技术] by (71.8m points)

angular10 - angular 11 display static text to dynamic value

I'm having 2 JSONs. The first one is having the format of the JSON value and the second one is having the actual value which is I want to display in the UI.

But I'm seeing the "application.appID" instead of 101. Does any help please?

Not working if label:"applicaiton.appID". I'm having label: "string"

working if label: 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>
question from:https://stackoverflow.com/questions/65947329/angular-11-display-static-text-to-dynamic-value

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If I understand right, what you're trying to do is to interpolate based on a string expression coming from a json. This is not something that you can do by just using the {{ }} construct. Here's why:

(For simplicity I will use div instead of mat-label)

In theory, this line would solve your problem

<div>{{this[json1.label]}}</div>

Just that it doesn't work since the inner json1.label part is not expanded/evaluated as expected.

Even if we manually write it as an explicit string, it still doesn't give us 101.

<div>{{this['application.appID']}}</div>

The only way to make such a syntax work would be to chain the field indexers, but that doesn't help us with using json1.label as the 'path' of the object and inner field.

<div>{{this['application']['appID']}}</div> // this returns 101, but it's not helpful for us...

So as you can see, pure html interpolation can't really help us achieve our goal. Instead, we should create a helper method inside the .component.ts file:

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;
  }
}

The new accessPropertyByString() method can be now used in the html template like this:

<div>{{accessPropertyByString(json1.label)}}</div>

Which finally returns 101 as expected.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...