简体   繁体   中英

Find an element by its id in the html file

I have an array

items = [{
"id" : 1,
"name": "peter"},
{
"id" : 2,
"name": "john"}
    ...
]

I am trying to find an item in the html file by the id based on that, I am trying to hide and element.

It can be easily done in js file, but I am trying to see if there is an easy way to do it in html file

You can add a template selector to the element

<input #myElement>

Then you can add a reference in your ts file

@ViewChild('myElement') myInput: ElementRef<HtmlInputElement>;

Or even reference the element directly in the template

<button (click)="myElement.focus()"></button>

If you want to hide an item, lets say its index is 2, you can do something like this in the HTML

<ng-container *ngFor="let eachItem of allArrayItems; let index=i">
  <div *ngIf="i != 2">  // This ngIf will be hidden if the index is 2
     whatever logic
  </div>
</ng-container>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM