File tree Expand file tree Collapse file tree 2 files changed +50
-10
lines changed
src/material/schematics/ng-generate/mdc-migration/rules Expand file tree Collapse file tree 2 files changed +50
-10
lines changed Original file line number Diff line number Diff line change @@ -190,6 +190,41 @@ describe('#visitElements', () => {
190190 it ( 'should add value to existing attribute that does not have a value' , async ( ) => {
191191 runAddAttributeTest ( '<a add></a>' , '<a add="val"></a>' ) ;
192192 } ) ;
193+
194+ it ( 'should handle all forms of indentation' , async ( ) => {
195+ runAddAttributeTest (
196+ '<a *ngFor="let item of items">' ,
197+ '<a add="val" *ngFor="let item of items">' ,
198+ ) ;
199+ runAddAttributeTest (
200+ `
201+ <a
202+ *ngFor="let item of items">` ,
203+ `
204+ <a
205+ add="val"
206+ *ngFor="let item of items">` ,
207+ ) ;
208+ runAddAttributeTest (
209+ `
210+ <a *ngFor="let item of items"
211+ >` ,
212+ `
213+ <a add="val" *ngFor="let item of items"
214+ >` ,
215+ ) ;
216+ runAddAttributeTest (
217+ `
218+ <a
219+ [attr]="
220+ val">` ,
221+ `
222+ <a
223+ add="val"
224+ [attr]="
225+ val">` ,
226+ ) ;
227+ } ) ;
193228 } ) ;
194229
195230 describe ( 'remove attribute tests' , ( ) => {
Original file line number Diff line number Diff line change @@ -158,19 +158,24 @@ export function updateAttribute(
158158 const prefix = html . slice ( 0 , index ) ;
159159 const suffix = html . slice ( index ) ;
160160 const attrText = newValue ? `${ name } ="${ newValue } "` : `${ name } ` ;
161+ const indentation = parseIndentation ( html , node ) ;
162+ return prefix + indentation + attrText + suffix ;
163+ }
161164
162- if ( node . startSourceSpan . start . line === node . startSourceSpan . end . line ) {
163- return ` ${ prefix } ${ attrText } ${ suffix } ` ;
164- }
165+ function parseIndentation ( html : string , node : TmplAstElement ) : string {
166+ let whitespace = '' ;
167+ let startOffset = node . startSourceSpan . start . offset + node . name . length + 1 ;
165168
166- const attr = node . attributes [ 0 ] ;
167- if ( attr ) {
168- const ctx = attr . sourceSpan . start . getContext ( attr . sourceSpan . start . col + 1 , 1 ) ! ;
169- const indentation = ctx . before ;
170- return prefix + indentation + attrText + suffix ;
171- }
169+ // Starting after the start source span's tagname,
170+ // read and store each char until we reach a non-whitespace char.
172171
173- return prefix + attrText + suffix ;
172+ for ( let i = startOffset ; i < node . startSourceSpan . end . offset - 1 ; i ++ ) {
173+ if ( ! / \s / . test ( html . charAt ( i ) ) ) {
174+ break ;
175+ }
176+ whitespace += html . charAt ( i ) ;
177+ }
178+ return whitespace || ' ' ;
174179}
175180
176181/**
You can’t perform that action at this time.
0 commit comments