如何扩展指令模板

问题描述

我有一个带有模板的指令,该指令可以在90%的场景中工作。但是,在某些情况下,我需要将其他字段添加到模板中。有没有一种方法可以扩展或修改现有的html模板,从而可以在不重建现有模板的90%的情况下添加其他字段

解决方法

在模板中放置ng-content

放置在components标签内的内容将显示在您具有ng-content的位置

void uploadJoystickPosition(JoystickPosition position){

   Timer.periodic(new Duration(seconds: 1),(Timer t) {
      DataModel dataModel = DataModel(1,getTimeInSeconds());
      dataModel.joystickPosition = position;
      debugPrint("Distance: ${position.distance}");
      uploadData(dataModel).then(uploadResponse,onError: uploadError);
   });
}

或者您可以传递模板

在您的组件中,您可以使用模板作为输入

<your-component>
  This content will appear where the ng-content tag is in your component's template
</your-component>

和模板中

@Input()
myTemplate: TemplateRef<any>;

您可以通过传递它

<ng-container *ngTemplateOutlet="myTemplate" *ngIf="myTemplate"></ng-container>