Sidhant Rajora
Sidhant Rajora

Reputation: 337

How to init component with click event in Angular5

I want to init a component when I click on div, here is my code

in html file

<li *ngFor="let contact of contactList">
<div (click)="anyFunctionName($event,contact.id)">
</div></li>

<component-selector></component-selector>

in ts file

anyFunctionName(event,id):any{
   // I will do some stuff, 
and output will be goes to another component html file, 
that will call another component <component-selector></component-selector> and display the output there
 } 

any idea ?

Thanks

Upvotes: 0

Views: 3362

Answers (2)

Preeti Rana
Preeti Rana

Reputation: 1

Add a boolean variable and initialize it as false in your component like this:

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

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {

  showthatDiv: boolean;
  ngOnInit() {

    this.showthatDiv = false;
  }

  anyFunctionName(event, id): any {
    this.showthatDiv = true;
  }

  public contactList: any[] = [{
    "id": 1,
    'name': 'name1'
  }, {
    "id": 2,
    'name': 'name2'
  }, {
    "id": 3,
    'name': 'name3'
  }];
}

and in your html you just need to bind that property:

<li *ngFor="let contact of contactList">{{contact.name}}
  <div (click)="anyFunctionName($event,contact.id)"> <button>hello </button>
  </div>
</li>

<component-selector [isOpen]="showthatDiv"></component-selector>

Upvotes: 0

Jannomeister
Jannomeister

Reputation: 629

You could create a attribute to your component.

ts file

 anyFunctionName(event,id):any{
   this.myVar = id;
 }

html file

<component-selector [myVar]="myVar"></component-selector>

your componenent-selector ts file

@Input('myVar') id: number;

ngAfterViewInit() { console.log(this.id) }

you can import Input in angular-core. Hope that helps.

Upvotes: 1

Related Questions