gog
gog

Reputation: 13008

How to change an angular2 html dynamically?

Im trying to find a way to change some html lines of a component dynamically.

<li *ngFor="p in persons" [attr.id]="p.id">
   <span> {{ p.name }} </span>                      
   <a (click)="getAge(p.id)">Get Age<a/>     
</li>

If the user clicks on the Get Age link i would like to replace the content inside of the corresponding li tag to something like:

<span> {{ p.OtherProperty }} </span> 
<a (click)="OtherMethod(p)">Call OtherMethod<a/>

I found that ComponentFactoryResolver to create dynamic components, but i found it too overwhelming for just 2 lines of html. And i tried to change it by hand using jquery but it does not work to create the event bindings:

getAge(id) { 
    //some work
    //remove the corresponding <li> content
    $('#' + id).append('<a (click)="getAnotherValue(p.name)">GetAnotherValue<a/>');
    $('#' + id).append('<span> {{ p.age}} </span>'); //this obviously doesnt work. But thats the ideia.
 }

So how can i replace some html tags with angular attributes dynamically?

Upvotes: 1

Views: 1811

Answers (2)

SrAxi
SrAxi

Reputation: 20015

You could access the person's Object property dynamically like this:

object[property]; // Where property is a string
// If property equals 'name', the above sentence would equal this:
object.name; // or `object['name'];`

So, following your example, you could do this:

export class App {
  persons = [
    {
     id: 1,
     name: 'John',
     age: 25
    },
    {
     id: 2,
     name: 'Mike',
     age: 30
    }
  ];
  selectedProperty = 'name';

  constructor() {
  }

  getProperty(prop) {
    this.selectedProperty = prop;
  }
}

And in your template you could:

<div>
  <li *ngFor="let p of persons" [attr.id]="p.id">
    <span> {{ p[selectedProperty] }} </span>
    <br>
  </li>
  <button (click)="getProperty('age')">Get Age</button> 
  <button (click)="getProperty('name')">Get Name</button>
</div>

If I understood well, this should do the trick. You can't use ngIf because if you have 60 properties or persons then will be somewhat caothic.

Check the Plunker

Upvotes: 1

Subtain Ishfaq
Subtain Ishfaq

Reputation: 841

Use ngIf to activate the code as shown:

     <li *ngFor="p in persons" [attr.id]="p.id">

        <div *ngIf=!p?.touched>

             <span> {{ p.name }} </span>
             <a (click)="getAge(p)">Get Age<a/>
        </div>

        <div *ngIf=p?.touched>
            <span> {{ p.age}} </span> 
            <a (click)="getAnotherValue(p.name)">GetAnotherValue<a/>
       </div>  

     </li>

    isGetAgeClicked=false;

        getAge(person) { 
            //some work
            //remove the corresponding <li> content
         person.touched=true
         }

Upvotes: 0

Related Questions