如何在 angular2 中为组件 html 中的元素触发 onload 事件 [英] how do I fire onload events for elements within component html in angular2

查看:35
本文介绍了如何在 angular2 中为组件 html 中的元素触发 onload 事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个二合一问题.

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

接下来是一个涉及在组件内注入ElementRef的问题.现在,文档 告诉我使用 'nativeElement' 财产不是很好的路要走.我真的不明白为什么.在组件中引用元素是一件好事,不是吗?还是我在监督关注点分离?我问是因为如果我的第一个问题不是一个选项,我想使用这个元素引用在 OnInit 类的 ngOnInit 函数中对我想要的 onload 触发元素进行 querySelection.

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

导出类 HomeComponent 实现 OnInit{公共类别:类别[];公共项目:项目[];构造函数(公共元素:ElementRef,私人_categoryService:类别服务,私有_itemService: ItemService,私有_router:路由器){}公共 registerDropdown(元素:HTMLElement):无效{控制台日志(元素);}私有 getCategories(): 无效{this._categoryService.getAll().then((categories:Category[])=> this.categories = Categories);}私有 getItems(): 无效{this._itemService.getAll().then((items:Item[])=> this.items = items);}公共 ngOnInit(): 任何{this.getCategories();this.getItems();}}

<div id="搜索"><div class="容器"><!-- 有问题的 div,[ngModel] 是黑暗中的一个镜头--><div #myDiv class="下拉类别" [ngModel]="registerDropdown(myDiv)"><span class="placeholder">选择器类别</span><div class="the-drop"><ul class="ul"><li *ngFor="#category of category"><input type="checkbox"/>{{category.long}}

解决方案

有关加载事件,请查看 这篇文章 从新手错误 #2 开始.

对于一般事件,我发现 EventEmitter 作为子组件(自定义标记标签)告诉父组件关于子事件的一种方式非常有用.在子进程中,创建一个自定义事件(一个用 @Output() 装饰的类变量),它会在您确定时 .emit() ,并且可以包含您的 EventEmitter 的参数指定的 .然后父级可以处理自定义事件并访问您在 $event 中捆绑的参数.我正在使用 Angular 2 快速入门文件.

脚本:

import {Component, Output, EventEmitter} from '@angular/core';@成分({选择器:'我的孩子',templateUrl: 'app/my-child.component.html'})导出类 MyChildComponent {@Output() childReadyEvent: EventEmitter= new EventEmitter();ngOnInit(){//执行任何代码行来初始化子进程console.log("第二次执行");//最后,this.childReadyEvent.emit("来自孩子的字符串");}}

标记:

我是家长

<my-child (childReadyEvent)="parentHandlingFcn($event)"></my-child>

脚本:

import {Component} from '@angular/core';从 './my-child.component' 导入 {MyChildComponent};@成分({选择器:'我的父母',templateUrl: 'app/my-parent.component.html',指令:[MyChildComponent]})导出类 MyParentComponent {ngOnInit(){console.log("这里先执行");}parentHandlingFcn(receivedParam: 字符串) {console.log("第三次执行," + receivedParam);//来自孩子的字符串}}

注意:你也可以尝试 EventEmitter.emit(this)

So this is a 2 in 1 question.

First, I am trying to fire a function when an element, within a components html, loads. I tried it numerous ways, like: <div [onload]="myFunction()"> this however results in the function being called multiple times, 10 to be exact. My guess is this is not the way to go, but I am not familiar enough to get it working properly. Also I would like to send the element along as a parameter. For example doing <div #myDiv (click)="myFunction(myDiv)"> does work, but obviously this isn't fired onload of said element. Whats the proper way here, or am I obligated to do a querySelector...

Next is a question involving the injection of the ElementRef within the component. Now, the docs tell me that using the 'nativeElement' property is not quite the way to go. I don't really understand why. Having a reference to the element in your component is a good thing, is it not? Or am I overseeing a separation of concern thing? I am asking because if my first question is not an option, I would like to use this element reference to do a querySelection of my desired onload firing elements in the ngOnInit function of the OnInit class.

All information is welcome, seeing the angular2 docs are not quite complete. Thank you.

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>

解决方案

For loading events, check out this article starting at rookie Mistake #2.

For general events, I found EventEmitter to be useful as a way for child components (custom markup tags) to tell the parent component about the child's events. In the child, create a custom event (a class variable decorated with @Output() ) which will .emit() whenever you determine, and can include parameters of your EventEmitter's specified <data type>. Then the parent can handle the custom event and access the parameters that you bundled within $event. I am using the Angular 2 quickstart files.

Child Script:

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

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

Parent Script:

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
  }

}

Note: you could also try EventEmitter<MyChildComponent> with .emit(this)

这篇关于如何在 angular2 中为组件 html 中的元素触发 onload 事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆