gpt4 book ai didi

javascript - 从指令 Angular 加载垫子图标

转载 作者:行者123 更新时间:2023-12-04 17:31:52 24 4
gpt4 key购买 nike

我很难从 Angular Material 加载图标组件。我想要实现的是附加一个可点击的图标,它使用这样的指令清除输入。

<input appClearInput></input>

问题是组件本身使用适当的 Material 类加载到模板中,但未呈现 SVG。图标的功能和位置很好,但问题是 SVG 没有添加到组件中,因此它显示为空白。

这是我指令中的代码:

import { Directive, Renderer2, ElementRef, OnInit, ViewContainerRef, ComponentFactoryResolver, ChangeDetectorRef } from '@angular/core';
import { NgControl } from '@angular/forms';
import { MatIcon } from '@angular/material';

@Directive({
selector: '[appClearInput]'
})
export class ClearInputDirective implements OnInit {
constructor(
private elementRef: ElementRef,
private renderer: Renderer2,
private control: NgControl,
private factory: ComponentFactoryResolver,
private vcRef: ViewContainerRef
} {}

ngOnInit() {
this.createComponent();
}

createComponent() {
this.vcRef.clear();

const factory = this.factory.resolveComponentFactory(MatIcon);
const matIcon = this.vcRef.createComponent(factory);
matIcon.instance.svgIcon = 'icon-cross';

const matIconEl = matIcon.injector.get(MatIcon)._elementRef.nativeElement;
this.renderer.setAttribute(matIconEl, 'svgIcon', 'icon-cross');
this.renderer.setStyle(matIconEl, 'cursor', 'pointer');
this.renderer.setStyle(matIconEl, 'outline', 'none');
this.renderer.listen(matIconEl, 'click', (e) => this.control.reset());

const parent = this.elementRef.nativeElement.parentNode;
const parentParent = this.renderer.parentNode(parent);

this.renderer.appendChild(parentParent, matIconEl);
}

我假设它不起作用,因为我在组件实例化后配置组件并且不会再次呈现组件。如果我在 instance._iconRegistry 下记录 ComponentRef,图标列表就在那里。

感谢任何帮助,谢谢。

最佳答案

你所要做的就是在图标上设置innerHTML

const searchIcon = this.viewContainer.createComponent<MatIcon>(searchIconResolver);
searchIcon.instance._elementRef.nativeElement.innerHTML = 'search';

关于javascript - 从指令 Angular 加载垫子图标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58847235/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com