I wrote this snippet and I’m looking for a way to edit the import line at the head of the file and add the correct additions to Component class.
"Angular Lifecycle Hooks": {
"prefix": "nglifecycle",
"body": [
"ngOnChanges() {",
"t// called before any bindings are made and before ngOnInit()",
"t// Here you can access the change detection results, and make any updates you want.",
"tconsole.log('ngOnChanges');",
"}",
"",
"ngOnInit() {",
"t// called once after the first ngOnChanges()",
"tconsole.log('ngOnInit');",
"}",
""
],
"description": "Angular Lifecycle Hooks Snippet"
}
Is there a way to do so?
Example for what I’m trying to achieve:
The snippet generate the text in the body tag, let’s say use it in line number 15. And I have this line, near the top of the file
import {Component} from '@angular/core'
I’m looking for a way that the snippet will update that line to
import {Component, OnInit, OnChange} from '@angular/core'
You see it is adding OnInit
and OnChange
which were added in the snippet body as ngOnChnages()
and ngOnInit()
.
2
Answers
You cannot do that solely with built-in functionality, but it is pretty easy with an extension. For example, Find and Transform (disclaimer: I wrote it), allows you to insert the snippet AND do a find and replace elsewhere in the document.
Using this keybinding (in your
keybindings.json
):Your
Angular Lifecycle Hooks
snippet is still located in some snippets file.The keybinding first inserts the snippet at the cursor and then does a find/replace for your
import {Component} from '@angular/core'
text.Note: if your langID is not
javascript
swap that part with your file’s language identifier – click on the language in the lower right-hand corner of the window and see the language ID, in parentheses like(javascript)
– just use the part in the parentheses.The regex
find
works if there are leading or trailing spaces in the{}
, andComponent
does not need to be there already. The additionsonInit
andonChange
will simply be added to whatever is already there. If need be, the regex could be modified to handle other cases.Snippet is an elementary functionality to add some text with modification of selected part of document and some other smple things. It doesn’t know anything about rest part of your document. But since you added
vscode-extensions
tag, maybe you can write your own simple extension doing the things you want 🙂 With its help you can modify document after snippet was inserted