I'm using ts-morph library and I want to insert in the declarations a component:
This is what I have:
@NgModule({
declarations: [],
imports: [],
providers: [],
})
This is what I want:
@NgModule({
declarations: [ExampleComponent],
imports: [],
providers: [],
})
I try this, but no results:
const decorator = classDeclaration.getDecorator("NgModule");
const arg = decorator.getArguments()[0];
const declarationsProp = arg.getDescendants()
.find(d => d.getKind() === SyntaxKind.PropertyAssignment &&
(d.compilerNode as ts.PropertyAssignment).name === "declarations");
const array = declarationsProp.getFirstChildByKindOrThrow(SyntaxKind.ArrayLiteralExpression);
const closeBracketToken = array.getLastChildByKindOrThrow(SyntaxKind.CloseBracketToken);
sourceFile.insertText(closeBracketToken.getPos(), `, "something new!"`);
And these other solution but I couldn't find a way to insert the component
const classDeclaration = sourceFile
.getClasses()
.find(
(classDeclaration) =>
classDeclaration.getName() === 'ExampleModule'
);
(classDeclaration.getDecorator('NgModule').getStructure()
.arguments as any[]).forEach((element) => {
addLog(LogType.Info, LogMode.Always, element);
});