Pismotality
Pismotality

Reputation: 2289

Passing data from HTML to component Angular 4

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.

Upvotes: 3

Views: 36102

Answers (2)

ttfreeman
ttfreeman

Reputation: 5523

To pass the data from HTML (template) to TS (component) you can either use two-way data binding by syntax [(ngModel)], or getElementbyID methd. You can learn more about ngModel here.

Example.

HTML:

<input type="text" name="someInput" [(ngModel)]="someInput">

TypeScript:

someInput: String = "";

Upvotes: 3

Mohammad Tauqir
Mohammad Tauqir

Reputation: 1815

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
    }
}

Upvotes: 3

Related Questions