【问题标题】:How to reduce line for viewchild in angular 8?如何在角度 8 中减少 viewchild 的线?
【发布时间】:2020-01-31 22:13:34
【问题描述】:

我的项目中有很多 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


【解决方案1】:

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

【讨论】:

【解决方案2】:

根据你的stackblitz,要修改所有元素,你可以创建一个指令:

@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

【讨论】:

  • 你只写了一个..我们如何使用多个元素引用?
猜你喜欢
  • 2018-12-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-23
  • 1970-01-01
  • 2014-03-09
  • 2023-02-22
  • 2020-06-12
相关资源
最近更新 更多