Angular7Javascript

How to set and get div attribute value on button click in Angular 7?

Views

Hello to all, welcome to therichpost.com. In this post, I will tell you, How to set and get div attribute value on button click in Angular 7?

If you are new in Angular 7, then you can check my old post to familiar with Angular 7.

I am getting and setting div attribute value with simple Javascript getAttribute and setAttribute method and this seems very easy.


How to set and get div attribute value on button click in Angular 7?

Here I am going show you working code snippet please follow be carefully:


1. Here is the code, you can add into your component html file like I added into app.component.html file:

For looking good, I just added bootstrap CDN, but you can remove this or you want to add bootstrap into you Angular 7 application, then please follow this post Add Bootstrap to Angular 7.

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<div class="jumbotron text-center" data-id="2">
  <h1>Attribute value is :</h1>
  <h3>{{ attrval }}</h3> 
</div>
how to set and get div attribute value on button click in Angular 7
http://prntscr.com/m8a4bj
<div class="container">
  <div class="btn-group">
    <button (click)="getVal()" type="button" class="btn btn-primary">Get Div Attribute Value</button>
    <button (click)="setVal()" type="button" class="btn btn-primary">Set Div Attribute Value</button>
  </div>
</div>

2. Here is the code, you need to add your component.ts file like I added into app.component.ts file:

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'angulartricks';
  attrval : any;
  
  getVal(){
  	var x = document.getElementsByClassName("jumbotron")[0].getAttribute("data-id");
  	alert(x);
  }

  setVal(){
  	document.getElementsByClassName("jumbotron")[0].setAttribute("data-id", "3");
  	this.attrval = document.getElementsByClassName("jumbotron")[0].getAttribute("data-id");
  }

  ngOnInit()
  {
  	this.attrval = document.getElementsByClassName("jumbotron")[0].getAttribute("data-id");
  }
}

 

If you have any query related to this post then you can comment below or you can ask question.

Harjas,

Thank you

Ajay Malhotra
the authorAjay Malhotra
Hello to all. Welcome to therichpost.com. Myself Ajay Malhotra and I am full stack developer. I love coding. I know Wordpress, Core php, Angularjs, Angular 2, Angular 6, Angular 7, laravel, Codeigniter, Shopify, Squarespace, Jquery, Google Map Api, Vuejs, Reactjs, Bigcommerce etc.

Leave a Reply

Positive SSL