首页 文章

如何为angular2中的组件html中的元素触发onload事件

提问于
浏览
7

所以这是一个二合一的问题 .

首先,我试图在组件html中的元素加载时触发函数 . 我尝试了很多方法,例如: <div [onload]="myFunction()"> 但这会导致函数被多次调用,确切地说是10 . 我的猜测是这不是要走的路,但我还不够熟悉,无法让它正常工作 . 另外,我想将元素作为参数发送 . 例如,做 <div #myDiv (click)="myFunction(myDiv)"> 确实有效,但显然这不会触发所述元素的onload . 什么是正确的方式,或者我有义务做一个querySelector ...

接下来是涉及在组件内注入ElementRef的问题 . 现在,the docs告诉我,使用'nativeElement'属性并不是一个好办法 . 我真的不明白为什么 . 在组件中引用元素是一件好事,不是吗?还是我在监督关注事项的分离?我问,因为如果我的第一个问题不是一个选项,我想使用这个元素引用来在OnInit类的ngOnInit函数中执行我想要的onload触发元素的querySelection .

欢迎所有信息,看到angular2文档不完整 . 谢谢 .

export class HomeComponent implements OnInit
{
    public categories: Category[];
    public items: Item[];

    constructor
    (
        public element: ElementRef,
        private _categoryService: CategoryService,
        private _itemService: ItemService,
        private _router: Router
    ){}

    public registerDropdown(element:HTMLElement): void
    {
        console.log(element);
    }

    private getCategories(): void
    {
        this._categoryService.getAll().then((categories:Category[])=> this.categories = categories);
    }

    private getItems(): void
    {
        this._itemService.getAll().then((items:Item[])=> this.items = items);
    }

    public ngOnInit(): any
    {
        this.getCategories();
        this.getItems();
    }
}
<div id="home">

    <div id="search">
        <div class="container">

            <!-- div in question, the [ngModel] is a shot in the dark -->
            <div #myDiv class="dropdown category" [ngModel]="registerDropdown(myDiv)">
                <span class="placeholder">Selecteer categorieën</span>
                <div class="the-drop">
                    <ul class="ul">
                        <li *ngFor="#category of categories">
                            <input type="checkbox" />{{category.long}}
                        </li>
                    </ul>
                </div>
            </div>
          
        </div>
    </div>
  
</div>

3 回答

  • 0

    如需加载活动,请查看this article,从菜鸟错误#2开始 .

    对于一般事件,我发现 EventEmitter 可用作子组件(自定义标记标记)的方式,以告知父组件有关子事件的事件 . 在子项中,创建一个自定义事件(一个用 @Output() 修饰的类变量),每当您确定时它将 .emit() ,并且可以包含EventEmitter指定的 <data type> 的参数 . 然后,父级可以处理自定义事件并访问您在 $event 中捆绑的参数 . 我正在使用Angular 2快速入门文件 .

    Child 脚本:

    import {Component, Output, EventEmitter} from '@angular/core';
    @Component({
      selector: 'my-child',
      templateUrl: 'app/my-child.component.html'
    })
    export class MyChildComponent {
      @Output() childReadyEvent: EventEmitter<string> = new EventEmitter();
    
      ngOnInit(){
        //do any lines of code to init the child
        console.log("this executes second");
        //then finally,
        this.childReadyEvent.emit("string from child");        
      }
    }
    

    Parent 加价:

    <h3>I'm the parent</h3>
    <my-child (childReadyEvent)="parentHandlingFcn($event)"></my-child>
    

    Parent 脚本:

    import {Component} from '@angular/core';
    import {MyChildComponent} from './my-child.component';
    
    @Component({
      selector: 'my-parent',
      templateUrl: 'app/my-parent.component.html',
      directives: [MyChildComponent]
    })
    export class MyParentComponent {
    
      ngOnInit(){
        console.log("this executes first");
      }
    
      parentHandlingFcn(receivedParam: string) {
        console.log("this executes third, with " + receivedParam); //string from child
      }
    
    }
    

    注意:您也可以尝试使用 .emit(this) EventEmitter<MyChildComponent>

  • 0

    您可以使用 Query 获取 div 的实例,然后在 ngOnInit 中触发 registerDropdown 方法并从 QueryList<ElementRef> 传入 nativeElement

    export class HomeComponent implements OnInit{
      public categories: Category[];
      public items: Item[];
    
      constructor
      (
        public element: ElementRef,
        private _categoryService: CategoryService,
        private _itemService: ItemService,
        private _router: Router,
        @Query('myDiv') private elList: QueryList<ElementRef>
      ){}
    
      public registerDropdown(element:HTMLElement): void
      {
        console.log(element);
      }
    
      ...
    
      public ngOnInit(): any
      {
        this.getCategories();
        this.getItems();
        this.registerDropdown(elList.first.nativeElement);
      }
    }
    
  • 9

    在进一步阅读时,似乎实现 Spy 是实现这一目标的最佳方式:

    https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html#!#spy

相关问题