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

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


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"

Tags:

Angular