有没有可能简单地更新_viewContainer?
我正在尝试为材料按钮组件创建指令,通过点击回车键为提交表单添加隐藏的经典按钮。我需要在_viewContainer中添加简单的html,类似这样
import 'package:angular/angular.dart';
@Directive(
selector: '[kpMaterialSubmit]',
)
class KpMaterialSubmit {
final TemplateRef _templateRef;
final ViewContainerRef _viewContainer;
KpMaterialSubmit(this._viewContainer, this._templateRef);
@Input()
set kpMaterialSubmit(bool showButton) {
_viewContainer.clear();
if (showButton) {
_viewContainer.createEmbeddedView(_templateRef);
//THIS IS THE IMPORTANT PART
_viewContainer.createMyCustomView('<button class="hidden">Submit</button>');
} else {
_viewContainer.createEmbeddedView(_templateRef);
}
}
}
我已经做了类似的事情,它的工作。我不知道是否有更好的方法。
不直接使用html文本,而是创建一个组件。
在组件模板中添加导入。
import 'package:<your package>/<path to component>/<component source name>.template.dart';
然后用createComponent()方法添加组件(而不是createMyCustomView())。
_viewContainer.createComponent(<componentName>NgFactory);
就这样!
如果你需要对组件进行样式设计或添加任何属性,你可以获取引用并派生出HtmlElement实例。
ComponentRef _componentRef = _viewContainer.createComponent(<componentName>NgFactory);
HtmlElement element = _componentRef.location;
element.style.background = 'green';
element.setAttribute('value', 'text');