如何减少角度8中的视子线?

问题描述 投票:0回答:2

我的项目中有很多Viewchild行。如何减少行数。有什么办法吗?

请帮助找到解决方案。

app.component.ts:

@ViewChild('pRef') pRef: ElementRef;
@ViewChild('Ref') Ref: ElementRef;
@ViewChild('pR') pR: ElementRef;
@ViewChild('ef') ef: ElementRef;
@ViewChild('main') main: ElementRef;
@ViewChild('power') power: ElementRef;
@ViewChild('current') current: ElementRef;
@ViewChild('volt') volt: ElementRef;
@ViewChild('rm') rm: ElementRef;
@ViewChild('wire') wire: ElementRef;
@ViewChild('cable') cable: ElementRef;
@ViewChild('on') on: ElementRef;
@ViewChild('off') off: ElementRef;
@ViewChild('amp') amp: ElementRef;
@ViewChild('short') short: ElementRef;
@ViewChild('cap') cap: ElementRef;
typescript angular6 angular7 angular8
2个回答
0
投票

[我认为这是一个很好的叹息,表明您的app.component.ts知道并且做得太多。拆分责任并将逻辑委派给另一个子组件可能会很棒。或者,您可以创建一个指令(例如CollectorDirective),将其附加到要获取的所有DOM元素(例如:<someComponent your-directive-selector></someComponent>),然后在您的app.component.ts中使用类似以下的内容:@ViewChild(CollectorDirective) allElements: QueryList<CollectorDirective>;在this.allElements中,您将获得一系列附加了CollectorDirective的孩子。但是没有上下文,尚不清楚它是否正是您所需要的,以及它是否适用于某些用例。


0
投票

根据您的堆栈闪电,要修改所有元素,您可以创建一个指令:

@Directive({
  selector: '[myDiv]'
})
export class TextTransform implements AfterViewInit {

    constructor(private elem: ElementRef) {}

     ngAfterViewInit() {
        this.elem.nativeElement.innerHTML = ' !!My new Text!!';
     }
}

并将指令应用于元素:

<p myDiv> Start</p>

Here the example

© www.soinside.com 2019 - 2024. All rights reserved.