角度8:传递html作为输入变量

我们可以使用@Input传递输入道具或数据。我们还可以使用<ng-content>将html负载转储到child组件中。有什么办法可以将html作为输入传递。像@Input html1,@ Input html2一样,并在子类组件中使用它们?

假设我在子类中有这个html:

<div class='wrapper'>
  <div class="content1 exclusive-css-defined-to-this-component">
     <div>{$content1}</div>
  </div>
  <div class="content2 exclusive-css-defined-to-this-component-2">
    <div>{$content2}</div>
  </div>
</div>

我想传递$ content1和$ content2作为输入。

mixiumingxiaoxiao 回答:角度8:传递html作为输入变量

您可以将html放在类似

的字符串中
htmlStr = "<strong>This is an example</strong>";

并将其传递给服务:

this.whateverService.setHtml(this.htmlStr);

然后在接收组件中:

import { WhateverService } from 'src/app/shared/service/whatever.service';

export class ReceivingComponentThing implements OnInit {
 htmlExample = '';

constructor(private whateverService: WhateverService) {}
}

ngOnInit() {
 // have a getter/setter in service however you like
 this.htmlExample = this.whateverService.getHtmlExample();
}

在您的模板中:

<div [innerHtml]="htmlExample"><div>
,

我们可以使用 innerHTML 实现这一目标

演示此示例的示例,

parent.component.ts,

export class ParentComponent {
  htmlOneAsString = `
    <div>Welcome Text Header</div>
  `;

  htmlTwoAsString = `
    <div>Welcome Text Content</div>
  `;

  htmlAsString = `
    <div><div>${this.htmlOneAsString}</div><div>${this.htmlTwoAsString}</div></div>
  `;
}

parent.component.html,

<child [innerHTML]="htmlAsString"></child>

child.component.ts,

@Component({
  selector: 'child'
})
export class ChildComponent {
  @Input() htmlAsString: string;
}

child.component.html,

<div>{{htmlAsString}}</div>
,

我找到了解决方案,可以通过以下方式完成:

<div class='wrapper'>
  <div class="exclusive-css-defined-to-this-component">
     <div><ng-content select="[content1]"></ng-content></div>
  </div>
  <div class="exclusive-css-defined-to-this-component-2">
    <div><ng-content select="[content2]"></ng-content></div>
  </div>
</div>

我们可以像这样使用组件:

<wrapper>
   <div content>Any thing you want to put in content1</div>
   <div content2>Any thing you want to put in content2</div>
</wrapper>
本文链接:https://www.f2er.com/3155813.html

大家都在问