How to get values of Inputs through class name in

2019-06-10 22:58发布

I have group of input elements:

    <input type="text" name="firstName" class="mandate" />
    <input type="text" name="MiddleName" class="mandate" />
    <input type="text" name="lastName" class="mandate" />
    <input type="text" name="Address" class="mandate" />'

In Jquery, it is very easy to get values through Class or we can easily perform some common event on the basis of class that all input elements have like

$('.mandate').each(function(){
console.log("Some....")
});

But I am wandering How it will be done in Angular 2.I am a completely newbie in Angular 2.

2条回答
放我归山
2楼-- · 2019-06-10 23:13

you can use element reference (ElementRef) in angular and querySelector the way you used in jQuery.

  constructor(private elementRef: ElementRef) {
  }

  // this is inside any of the method
  // this is to select multiple 
  this.elementRef.nativeElement.querySelectorAll('.mandate');

  // this is to select single
  this.elementRef.nativeElement.querySelector('.mandate')
查看更多
Summer. ? 凉城
3楼-- · 2019-06-10 23:22

To solve this problem you can use the view children in your component. This will let you select all elements in the template similarly to how jquery does.

@ViewChildren('.mandate') mandates;

mandates.forEach((mandate) =>{
     //do something here
});

This will retrieve all elements with class mandate as an array and will update with angular change detection.

查看更多
登录 后发表回答