Rolando
Rolando

Reputation: 62634

How to add attributes to parent dom elements of component in angular2?

I have the following:

...
<div class="container">
  <div class="fancy">
    <fancybutton></fancybutton>
  </div>
  <button (click)="addAttribute()">Remove</button>
  <button (click)="remAttribute()">Add</button>
</div>

... My question is, How can I make it so that when the user hits "addAttribute()" it adds "testattribute" to the parent dom element of the component like this:

  <div class="fancy" testattribute="a">
    <fancybutton></fancybutton>
  </div>

This is my fancy-button component, below is the parent template that i have the fancy-button integrated in within the home.component.html:

@Component({
  selector: 'fancy-button',
  template: `<button>clickme</button>`
})
export class FancyButton {}

@Component({
  selector: 'home',  // <home></home>
  providers: [
    Title
  ],
  styleUrls: [ './home.component.css' ],
  templateUrl: './home.component.html'
})

Upvotes: 0

Views: 1776

Answers (2)

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

Reputation: 657416

<div class="container">
  <div class="fancy" [attr.testattribute]="isAttr">
    <fancybutton></fancybutton>
  </div>
  <button (click)="isAttr = true">Remove</button>
  <button (click)="isAttr = false">Add</button>
</div>

Upvotes: 1

user6882389
user6882389

Reputation:

I have a possible solution (untested at time of writing):

Add the name and value of the parameters to the addAttribute()call as follows:

addAttribute("testattribute", "a");

You'll also need to add this.parentElement to the beginning of the call:

this.parentElement.addAttribute("testattribute", a");

Let me know if this solution works for you.

Upvotes: 0

Related Questions