gpt4 book ai didi

javascript - 什么时候嵌入合适?

转载 作者:搜寻专家 更新时间:2023-10-30 21:51:34 25 4
gpt4 key购买 nike

例如,我正在 Angular2 中开发一个多选控件,其功能类似于 Select2或许多其他控件。

我首先通过定义下拉列表中包含的内容来定义我希望用户界面的外观,并提出了两个选项。

一种是使用@Input() s 用于选项:

<my-multi-select [options]="options"></my-multi-select>

...然后在 my-multi-select 的模板中:

<div class=option" *ngFor="let option of options">{{option.display}}</div>

另一个是使用嵌入,是这样的material2似乎是这样做的:

<my-multi-select>
<my-option *ngFor="let option of options" [value]="option"></my-option>
</my-multi-select>

...然后在 my-multi-select 的模板中:

<div class=select-container">
<ng-content select="my-option"></ng-content>
</div>

我对嵌入选项很满意,但是当我开始实际实现它时,发现很难绑定(bind)来自 my-option 的事件。至 my-multi-select .我可以想办法通知 my-select my-option 中发生的事情,就像使用 Observable ,或深入挖掘使用 @Output事件——但是当 @Input 时,这感觉就像试图将方形钉子塞入圆孔中变量可能更简单。

这让我想到了一个问题,这里的嵌入是否合适?更大的问题是,什么时候嵌入合适,什么时候使用嵌入将方钉塞入圆孔?

最佳答案

对于您的示例,比较这两种方法很简单,因为您只包含一个文本项作为嵌入的一部分。这使得使用 @Input() 变得微不足道并且很可能是最好的解决方案。

但是,想象一下您有多个元素要包含在子组件中的场景,每个元素都带有自定义 HTML 标记。使用 trasnclusion 这是微不足道的,但是使用 @Input() 它需要一些“hacks” 才能正确,并且不是很容易维护或扩展。


解释

以此为基础Todd Motto blog about transclusion作为引用,我们可以利用嵌入为我们的 titlecontent 部分提供更复杂的 HTML,而不会出现问题。

Transculsion Parent

<my-component>
<my-title>
<h1>This is the Component title!</h1>
</my-title>
<my-content>
And here's some awesome content.
<ul>
<li>First</li>
<li>Second</li>
</ul>
</my-content>
</my-component>

包容 child

<div class="my-component">
<div>
Title:
<ng-content select="my-title"></ng-content>
</div>
<div>
Content:
<ng-content select="my-content"></ng-content>
</div>
</div>

现在想象同样的场景,只使用 @Input() 来声明我们的元素。

我们从父级的绑定(bind)不是很友好,我们绝对不想为更复杂的场景这样做。

在我们的子组件中,我们必须使用 [innerHTML] 来绕过 Angular 中的插值编码。同样,这不是很容易扩展或维护。在我看来,这就是嵌入真正出色的地方。

输入父级

<my-component
[my-title]="<h1>This is the Component title!</h1>"
[my-content]="And here's some awesome content.<ul><li>First</li><li>Second</li></ul>">
</my-component>

输入 child

 <div class="my-component">
<div [innerhtml]="'Title:' + my-title"></div>
<div [innerhtml]="'Content:' + my-content"></div>
</div>

关于javascript - 什么时候嵌入合适?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42915425/

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