user8836786
user8836786

Reputation:

Angular - Is it possible to dynamically add attributes on button click

What I'm using

What I'm trying to do

What I have

What I'm not sure how to do

[phantomOp]="myItems" [myOper]="oper"

HTML

<div class="container">
  <ul>
    <li> Albums </li>
    <li> Dates </li>
    </ul>
</div>

<button (click)="addContainerAttributes"> Add Container Attributes </button>

What I would like the HTML to look like after a button click

<div class="container" [phantomOp]="myItems" [myOper]="oper">
  <ul>
    <li> Albums </li>
    <li> Dates </li>
  </ul>
</div>

TS

addContainerAttributes(){
  // Not entirely sure what to put here
}

Upvotes: 14

Views: 43992

Answers (2)

Chif
Chif

Reputation: 840

I ran into a similar situation recently. I wanted to dynamically add and remove the capture attribute on a FileInput. Now just the presence of the capture attribute and the File Input will fall to capture mode, so having the value as null or '' did not work for me.

This is how I finally got it to work. I used @ViewChild and ElementRef. In your case it would be something like:

<div #yourContainer class="container">
  <ul>
    <li> Albums </li>
    <li> Dates </li>
    </ul>
</div>

<button (click)="addContainerAttributes"> Add Container Attributes </button>

Then in the TS

import { Component, ElementRef } from '@angular/core';

@Component({
  selector: 'app-your-component',
  templateUrl: './your-component.component.html',
  styleUrls: ['./your-component.component.css']
})
export class YourComponent {
@ViewChild('yourContainer', {static:true}) yourContainer: ElementRef;

....

  addContainerAttributes(){
    // Not entirely sure what to put here
    this.yourContainer.nativeElement.setAttribute('phantomOp', myItems);
    this.yourContainer.nativeElement.setAttribute('myOper', oper);
  }

  // if you wish to completely remove the attribute dynamically
  removeContainerAttributes(){
    this.yourContainer.nativeElement.removeAttribute('phantomOp');
    this.yourContainer.nativeElement.removeAttribute('myOper');
  }
}

Upvotes: 5

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657376

Adding Angular specific markup added dynamically at runtime will just be ignored by Angular. Bindings like [phantomOp]="myItems" [myOper]="oper" are processed by Angular only when a component is compiled. Normally (with AoT) this is before you deploy your application.

How can I use/create dynamic template to compile dynamic Component with Angular 2.0? explains how to compile a component at runtime.

You can just introduce a field in your component

isClicked:boolean = false;

add this to your element statically

[phantomOp]="isClicked ? myItems : null" [myOper]="isClicked ? oper : null"

and in the click handler

(click)="isClicked=true"

Upvotes: 18

Related Questions