0

I am trying to work with anchors using angular i have done my research but no success so i am reaching out to you guys.

I have 3 components {NavbarComponent, RedComponent, BlueComponent} the NavbarComponent has 2 anchors. I want when i click on one of them it actually lead me to the right component

navbar.component.ts

  @Component({
  selector: 'navbar',
  template: `<ul>
    <li><a href="#red">Red</a></li>
    <li><a href="#blue">Blue</a></li>
  </ul>`
})
export class NavbarComponent {
  constructor() { }
}

red.component.ts

@Component({
  selector: 'red',
  template: '<div id="red">Red Component</div>'
})
export class RedComponent {
  constructor() { }
}

blue.component.ts

@Component({
  selector: 'blue',
  template: '<div id="blue">Blue Component</div>'
})
export class BlueComponent {
  constructor() { }
}

app.component.html

<navbar></navbar>
<red></red>
<blue></blue>

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { Routes, RouterModule } '@angular/router'; 
import { AppComponent } from './app.component';
import { NavbarComponent } from './navbar/navbar.component';
import { RedComponent } from './red/red.component';
import { BlueComponent } from './blue/blue.component';

@NgModule({
  declarations: [
    AppComponent,
    NavbarComponent,
    RedComponent
    BlueComponent
  ],
  imports: [
    BrowserModule,
    RouterModule.forRoot()
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

1 Answers1

0

To hyperlink to component's template, you need to assign an id attribute. You can do so by using @HostBinding -

@Component({
  selector: 'red',
  template: '<div id="red">Red Component</div>'
})
export class RedComponent {
  @HostBinding('id') id = 'red';
  constructor() { }
}

@Component({
  selector: 'blue',
  template: '<div id="blue">Blue Component</div>'
})
export class BlueComponent {
  @HostBinding('id') id = 'red';
  constructor() { }
}

Refer @HostBinding and @HostListener: what do they do and what are they for? for more details

Wand Maker
  • 18,476
  • 8
  • 53
  • 87