Angular2 ElementRef 实现低耦合高内聚 视图应用分离

本文探讨Angular中的ElementRef和Renderer如何帮助降低视图层与应用层的耦合,通过示例说明如何使用ElementRef获取DOM对象,并讨论在何时获取以及避免在初始化时遇到的问题。同时,介绍ViewChild装饰器的使用以及Renderer对象在分离视图和应用中的作用。
摘要由CSDN通过智能技术生成

为什么需要ElementRef

Angular一直在做的一件事情就是降低视图层和应用层之间的耦合,在应用层直接操作DOM,会导致应用层和视图层之间强耦合,导致我们不能将应用运行在不同的环境中。比如令js能够实现多线程的webWorker,在webWorker中,却不能直接操作DOM,angular为我们封装了一个对象,叫做ElementRef,能够获取到视图层中的native对象,比如在浏览器中,native对象就是DOM对象。

以下是Angular中的ElementRef的具体实现:

export class ElementRef {
   
  public nativeElement: any;
  constructor(nativeElement: any) { this.nativeElement = nativeElement; }
}

如何使用ElementRef

下面来看一个简单的例子,我们声明一个组件,我们要实现的功能是,点击点击按钮,根据输入框的输入值来更改子组件的颜色。
那么整个组件大概会是这个样子。

这里写图片描述

首先我们编写app.ts,也就是图上的parent component。

app.ts

import { Child } from './child.component';
import { bootstrap } from '@angular/platform-browser-dynamic';
import { Component, ViewChild, ElementRef } from '@angular/core';

@Component({
    selector:'app',
    template:`<div>
        <input #colorIndex type='text' />
        <button (click)='changeColor(colorIndex.value)'>change color</button>
        <child></child>
    </div>`,
    directives:[Child]
})
export class App{
    private defaultColor:string;
    private targetColor:string;

    constructor(private elementRef:ElementRef){
        //默认颜色初始化
        this.defaultColor = 'transparent';
    }

    //change color
    changeColor(value:string):void{
        console.log(value);
        this.targetColor = this.defaultColor || value;
        let Div = this.elementRef.nativeElement.querySelector('child div');
        Div.style.backgroundColor = value;
    }

}

bootstrap(App);

下面是子组件的代码,没有任何功能,只是简单的声明了一下样式。

child.component.ts

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

@Component({
    selector:"child",
    template:`<div></div>`,
    styles:[`
        div{
            width:100px;
            height:100px;
        }
    `]
})
export class 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值