简体   繁体   中英

DOMException: Failed to execute 'setAttribute' on 'Element': '[routerLink' is not a valid attribute name

So i have basically started a new angular Project and I'm making the navbar for it and here's the code

navbar.component.html:

<nav>
  <li class="navbar-list">
    <a [routerLink="/home-component"] [class="home-link"]>Home</a>
    <a [routerLink="/about.component"] [class="about-link"]>About</a>
  </li>
</nav>
<router-outlet></router-outlet>
// navbar.component.ts
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';

@Component({
  selector: 'app-navbar',
  templateUrl: './navbar.component.html',
  styleUrls: ['./navbar.component.scss']
})

export class NavbarComponent implements OnInit {

  constructor() { }

  ngOnInit(): void {

  }

}

this error occured after i add the [routerLink="abc"] attributes on the elements. And if you want to know there is nothing in home.component.html and about.component.html since this is self work-in-progress project and its just for fun!

HELPPP!

The binding is not used correctly in your snippet code. The square brackets [] should enclose the element property only (not the property and its value), like the following:

<nav>
  <li class="navbar-list">
    <a [routerLink]="'/home'" class="home-link">Home</a>
    <a [routerLink]="'/about'" class="about-link">About</a>
  </li>
</nav>
<router-outlet></router-outlet>

The brackets, [], cause Angular to evaluate the right-hand side of the assignment as a dynamic expression. Without the brackets, Angular treats the right-hand side as a string literal and sets the property to that static value.

That's useful if you have dynamic links, however in other cases you just need to pass a static value to the property, then, you can add it without square brackets, like the following:

<nav>
  <li class="navbar-list">
    <a routerLink="/home" class="home-link">Home</a>
    <a routerLink="/about" class="about-link">About</a>
  </li>
</nav>
<router-outlet></router-outlet>

Read more about binding in Angular:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM