'How can I use Angular schematics insert an element into array?
I am using Angular schematics to generate component automatically. There are 3 things I want to do:
- import component in module (done)
- insert something(such as '11') into an array
- add case code into switch
I have achieved the point one by addImportStatement as blow.
function getTsSourceFile(host: Tree, path: string) {
const buffer = host.read(path) as Buffer;
const content = buffer.toString();
const source = ts.createSourceFile(path, content, ts.ScriptTarget.Latest, true);
return source;
}
export function addImportStatement(tree: Tree, filePath: string, importName: string, importPath: string): void {
let source = getTsSourceFile(tree, filePath);
const importChange = insertImport(source, filePath, importName, importPath) as InsertChange;
if (!(importChange instanceof NoopChange)) {
const recorder = tree.beginUpdate(filePath);
recorder.insertLeft(importChange.pos, importChange.toAdd);
tree.commitUpdate(recorder);
}
}
But I don't know how to achieve point 2 and 3. What I need is below
// before
const items = ['1', '2'];
// after
const items = ['1', '2', '11'];
// before
export function getComponent(index: typeof PageOrder[number]): {
question: Type<unknown>;
answer?: Type<unknown>;
title: string;
analyse?: boolean;
} {
switch (index) {
case '10':
return {
question: Question10Component,
answer: Answer10Component,
title: '父子组件',
analyse: true,
};
default:
throw new Error('The method getComponent() can not find valid components');
}
}
// after
export function getComponent(index: typeof PageOrder[number]): {
question: Type<unknown>;
answer?: Type<unknown>;
title: string;
analyse?: boolean;
} {
switch (index) {
case '10':
return {
question: Question10Component,
answer: Answer10Component,
title: '父子组件',
analyse: true,
};
case '11':
return {
question: Question11Component,
answer: Answer11Component,
title: 'some title',
analyse: true,
};
default:
throw new Error('The method getComponent() can not find valid components');
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
