How does Angular compiler process multiple template reference variables with the same name

1.1k views Asked by At

I want to start contributing to angular, I have an idea for a feature, I want the template compiler to issue a warning if a template contains two template variables of the same name. I think I managed to get close to the source files responsible: https://github.com/angular/angular/blob/master/packages/compiler/src/view_compiler/view_compiler.ts but couldn't quite find the spot, understandably. Is there anyone here who can guide me ?

1

There are 1 answers

0
Max Koretskyi On BEST ANSWER

You need to look into the _assertNoReferenceDuplicationOnTemplate method:

  _assertNoReferenceDuplicationOnTemplate(result: TemplateAst[], errors): void {
    const existingReferences: string[] = [];

    result.filter(element => !!(<any>element).references)
       .forEach(element => (<any>element).references.forEach((reference: ReferenceAst) => {
          const name = reference.name;
          if (existingReferences.indexOf(name) < 0) {
            existingReferences.push(name);
          } else {
            const error = new TemplateParseError(
                `Reference "#${name}" is defined several times`, reference.sourceSpan,
                ParseErrorLevel.ERROR);
            errors.push(error);
          }
        }));
  }

Angular compiler creates AST with one node type being ElementAST which has references property:

export class ElementAst implements TemplateAst {
  constructor(
      public name: string,
      public references: ReferenceAst[],
      ...

And this is the property that is checked in the _assertNoReferenceDuplicationOnTemplate function and if found the error is generated.