Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing data from HTML to component Angular 4

Tags:

angular

I'm new to Angular, and I'm trying to do something which sounds very simple, but which I'm finding very difficult. I've got an *ngFor statement which creates a new div for each item in the collection and displays a value in that div using double braces {{ }}. I want to pass that value into my component.ts but have been unable to figure out how to do so.

Here's one of the things I have tried:

HTML:

<div *ngFor="let auditType of auditTypes; let i=index">
          <br />
          <a (click)="filterByAuditType(auditType)">
              <div [selection]=auditType [id]="'AuditType' + i" class="filterChoices" (click)="highlightSelected($event)">{{auditType}}</div>
          </a>
</div>

The value of "auditType" is what I want to pass in to the component, so I can perform jQuery actions on it.

Component:

export class ComponentTeamsComponent implements OnInit, OnDestroy {
   @Input() selection: string;

 ngOnInit() {
this.checkIfSelected(this.selection);
}

checkIfSelected(selection: string): void {
    $('*').each(function() {
        if ($(this).hasClass('highlightMenu')) {
            if ($(this).attr('id').indexOf('AuditType') > -1) {
                this.filterByAuditType(selection);
            }
         ---  //more code
    }
});

My understanding now is that @Input won't work if the component is on the same level as the HTML (i.e., not a Child component). Please help if you know something that will work.

like image 724
Pismotality Avatar asked Mar 07 '26 06:03

Pismotality


1 Answers

See below example to understand the concept for *ngFor in angular 4.

HTML

<div *ngFor="let Country of countryList; let i=index" (click)="highlightSelected(Country)" name = "name">{{Country.name}}</div>

YourComponent.ts

export class ComponentTeamsComponent implements OnInit, OnDestroy {
   countryList:any[];
   ngOnInit() {


      this.countryList = [
        { name: "United States"},
        {name: "Australia"},
        {name: "Canada"},
        {name: "Brazil"},
        {name: "England"}
      ];
   }


    highlightSelected(selectedCountry) {
       console.log(selectedCountry.name);
       // your rest code goes here
    }
}
like image 199
Mohammad Tauqir Avatar answered Mar 08 '26 20:03

Mohammad Tauqir