【问题标题】:How to init component with click event in Angular5如何在Angular5中使用点击事件初始化组件
【发布时间】:2018-08-30 07:30:19
【问题描述】:

我想在点击 div 时初始化一个组件,这是我的代码

在 html 文件中

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

<component-selector></component-selector>

在ts文件中

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
 } 

有什么想法吗?

谢谢

【问题讨论】:

标签: typescript angular5


【解决方案1】:

你可以为你的组件创建一个属性。

ts 文件

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

html文件

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

您的组件选择器 ts 文件

@Input('myVar') id: number;

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

您可以在angular-core 中导入Input。希望对您有所帮助。

【讨论】:

    【解决方案2】:

    添加一个布尔变量并将其在组件中初始化为 false,如下所示:

    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'
      }];
    }
    

    在您的 html 中,您只需要绑定该属性:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-04
      • 1970-01-01
      • 2019-01-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多