英文:
Expose dependencies of a standalone component
问题
所有组件都是独立的。
我有一个使用输入指令的表单字段组件。我想在导入组件时导入该指令,而不必显式导入它。有点像模块的工作方式,但在独立模式下。
是否可能,如果是的话,如何?
@Component({
selector: 'my-app',
standalone: true,
imports: [CommonModule, FieldComponent, InputDirective], // ← 从这里移除指令
template: `
<app-field>
<input type="text" placeholder="Some text">
</app-field>
`,
})
@Component({
selector: 'app-field',
standalone: true,
imports: [InputDirective],
template: '<ng-content select="input"></ng-content>',
styleUrls: ['./field.component.css'],
})
@Directive({
selector: 'app-field input',
standalone: true,
})
export class InputDirective {
constructor() {
console.log('Here I am');
}
}
英文:
All the components are standalone.
I have a form-field component that uses an input directive. I would like to import the directive when I import the component, without having to explicitly import it. Kind of like how modules work, except in standalone mode.
Is it possible, and if so, how ?
@Component({
selector: 'my-app',
standalone: true,
imports: [CommonModule, FieldComponent, InputDirective], // ← Remove the directive from here
template: `
<app-field>
<input type="text" placeholder="Some text">
</app-field>
`,
})
@Component({
selector: 'app-field',
standalone: true,
imports: [InputDirective],
template: '<ng-content select="input"></ng-content>',
styleUrls: ['./field.component.css'],
})
@Directive({
selector: 'app-field input',
standalone: true,
})
export class InputDirective {
constructor() {
console.log('Here I am');
}
}
答案1
得分: 0
以下是翻译好的部分:
唯一的解决方法是对这种类型的导入(服务也有类似的用例)使用数组:
export const FIELD_IMPORTS = [FieldComponent, InputDirective];
@Component({
selector: 'my-app',
standalone: true,
imports: [CommonModule, ...FIELD_IMPORTS],
template: `
<app-field>
<input type="text" placeholder="Some text">
</app-field>
`,
})
英文:
The only workaround for this type of imports (there are similar use-cases with services) that I have found is to use an array:
export const FIELD_IMPORTS = [FieldComponent, InputDirective];
@Component({
selector: 'my-app',
standalone: true,
imports: [CommonModule, ...FIELD_IMPORTS],
template: `
<app-field>
<input type="text" placeholder="Some text">
</app-field>
`,
})
答案2
得分: 0
我刚刚看到了来自Alex Rickabaugh(angular团队成员)的tweet about this:
> 简短回答:不要这样做 - standalone的目的是依赖项是单独导入的,而不是捆绑在一起。
>
> 细微的回答:如果您有一些一起工作并需要一起添加的指令,请使用NgModule。
>
> 技术性回答:[HlmAccordion,...] as const
应该有效。
所以在你的情况下,最好坚持使用ngModules。
英文:
I just saw a tweet about this from Alex Rickabaugh (member of the angular team) :
> Short answer: don't - the point of standalone is that deps are
> imported individually and not bundled.
>
> Nuanced answer: if you have directives that work together and need to
> be added together, use an NgModule.
>
> Technical answer: [HlmAccordion, ...] as const
should work
So in your case you're better of sticking to ngModules.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论