How to pass data from angluar component to angular layout component - TagMerge
6How to pass data from angluar component to angular layout componentHow to pass data from angluar component to angular layout component

How to pass data from angluar component to angular layout component

Asked 7 months ago
1
6 answers

Your component has been created once and since it is not getting any new inputs, nothing is forcing it to be rerendered

1- Move your App Contract component onInit event code to OnChanges event instead

2- Inject the contract as an input in your component, so when ever contract changes the onChanges event will be called

3- You are emitting the contract from search using event emitter therefore you can grab it in html and pass it to the app contract component as input

3- Your Html should look like that

<app-contract-search (change)= "contract=$event"></app-contract-search>
<app-contract [contract]="contract"></app-contract>

4- Your new App Component ts code

public [input] contract: Contract;

5- you don't need to do getContract method or any further subscriptions because you will be duplicating the logic

Source: link

1

You can alter you app component ts to the following

@Component({
 selector: 'app-contract',
 templateUrl: './contract-layout.component.html',
 styleUrls: ['./contract-layout.component.css']
 })
 export class ContractComponent implements OnInit {

 public contract: Contract;
 public contractId: number;

 constructor(private router: ActivatedRoute, private http: HttpClient,
          private contractService: ContractService, private ChangeDetectorRef 
          changeDetector) { }


 ngOnInit(): void {

 // First get the product id from the current route.
  const routeParams = this.router.snapshot.paramMap;
  this.contractId = Number(routeParams.get('contractId'));

  console.log("Contract Id form url : " + this.contractId);

  this.GetContractByNumber(this.contractId);

}

GetContractByNumber(number: number) {
  this.contractService.getContractByContractNumber(number).subscribe(result => {
  this.contract = result;
  this.changeDetector.detectChanges();// this will force rerender your component 
}, error => {
  console.log(error)
});
}}

Source: link

1

I think you should do something like this:

in app-contract component

<app-contract-search (change)="GetContractByNumber($event.number)"><app-contract-search>

Source: link

0

// app.component.ts
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `
    <div class="app">
      <counter></counter>
    </div>
  `
})
export class AppComponent {
  initialCount: number = 10;
}
@Component({
  selector: 'app-root',
  template: `
    <div class="app">
      <counter [count]="initialCount"></counter>
    </div>
  `
})
export class AppComponent {
  initialCount: number = 10;
}
import { Component } from '@angular/core';

@Component({...})
export class CounterComponent {

  count: number = 0;

  increment() {
    this.count++;
  }

  decrement() {
    this.count--;
  }

}
import { Component, Input } from '@angular/core';

@Component({...})
export class CounterComponent {

  @Input()
  count: number = 0;

  increment() {
    this.count++;
  }

  decrement() {
    this.count--;
  }

}
@Component({
  selector: 'app-root',
  template: `
   <div class="app">
      <counter [init]="initialCount"></counter>
    </div>
  `
})
export class AppComponent {
  initialCount: number = 10;
}

Source: link

0

Header Service
@Injectable({
  providedIn: 'root',
})
export class HeaderService {
  private _title: string = 'Default Header Name';
  subject = new Subject();

  changeHeaderTitle(newTitle: string) {
    this._title = newTitle;

    this.subject.next(this._title);
  }

  clear() {
    this._title = 'Default Header Name';
    this.subject.next(this._title);
  }
}
Header Component
@Component({
  selector: 'kb-header',
  templateUrl: './header.component.html',
  // styleUrls: [ './app.component.css' ]
})
export class HeaderComponent implements AfterViewInit {
  name: string = 'Default header name';

  constructor(private headerService: HeaderService) {}

  ngAfterViewInit() {
    this.headerService.subject.subscribe((newTitle: string) => {
      this.name = newTitle;
    })
  }
}
Screen Component
@Component({
  selector: 'hello',
  template: `<h1>Hello {{name}}!</h1>`,
  styles: [`h1 { font-family: Lato; }`]
})
export class HelloComponent implements AfterViewInit {
  @Input() name: string;

  constructor(private headerService: HeaderService) {}

  ngAfterViewInit() {
    setTimeout(() => {
        this.headerService.changeHeaderTitle('pizza');
    }, 3000);
  }
}

Source: link

0

When we are building a scalable web application, then we need to send and retrieve data via routing. Let’s generate a couple of components to use for navigation on our previous example of routing articles 1.
ng generate component hotels
ng generate component hotel
ng generate component login
Angular allows us to navigate between different components mainly using two approaches. First, we can use the router link directive in a template and the second router object in the typescript component. We will demonstrate router navigation using both approaches on the following link.
http://localhost:4200/about
http://localhost:4200/hotels/
http://localhost:4200/hotels/id
We have already created routing.module.ts  and import the routing module in app.module.ts  in the previous example. Edit app-routing.module.ts to add a new routing for hotels and their children routes. We have hotels and its children route with hotels/: id. The slash in a route path is a dynamic value where we are passing hotel id.
import { LoginComponent } from './login/login.component';
import { HotelsComponent } from './hotels/hotels.component';
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { AboutComponent } from './about/about.component';
import { NavbarComponent } from './navbar/navbar.component';
import { EditHotelComponent } from './hotels/edit-hotel/edit-hotel.component';
import { HomeComponent } from './home/home.component';


const routes: Routes = [
  { path: '', component: HomeComponent },
  { path: 'login', component: LoginComponent },
  { path: 'about', component: AboutComponent },
  { path: 'navbar', component: NavbarComponent },
  {
    path: 'hotels', component: HotelsComponent, children: [
      { path: ':id', component: EditHotelComponent }
    ]
  }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }
How to pass data in angular route component 12 . ?Angular / By ngodup / May 12, 2021 October 5, 2021
<nav class="navbar navbar-inverse">
    <div class="container">
      <div class="navbar-header">
        <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
          <span class="sr-only">Toggle navigation</span>
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
        </button>
      </div>
      <div id="navbar" class="collapse navbar-collapse">
        <ul class="nav navbar-nav">
          <li><a [routerLink]="['/']">Home</a></li>
          <li><a [routerLink]="['/about']">About</a></li>
          <li><a [routerLink]="['/hotels']">Hotels</a></li>
        </ul>
      </div>
    </div>
  </nav>
Angular allows different ways of passing data between components. We will first learn and demonstrate the state object of navigate() method, this support came since the release of Angular 7.2. We want to send data from home to about components using the state object as shown in the above picture. When a user clicks on the send button in the home component it will call the sendRouteObject () method. This method sends data as an object and navigates to about component.
import { Component } from '@angular/core';
import { Router } from '@angular/router';

@Component({
  selector: 'app-home',
  template: `
  <div class="container">
    <div class="row">
        <div class="col-md-6">
            <h4>1. In template, route to hotels/id where id is 2</h4>
        </div>
        <div class="col-md-4">
            <button class="btn btn-primary" [routerLink]="['/hotels/' + '2']">Navigation using RouterLink in template</button>
        </div>
    </div>
    <div class="row">
        <div class="col-md-6">
            <h4>2. Programmatically route to hotels with params id </h4>
        </div>
        <div class="col-md-4"> <button class="btn btn-primary" (click)="routeToHotelId(2)">
            Navigation using router object in typescript</button>
        </div>
    </div>
</div>

<div class="mt">
    <h4>3. Send data from search to about component.</h4>
    

{{ "{ site: 'edupala.com' frontEnd: { name: Angular version: 12 } }" }}

<button class="btn btn-primary" (click)="sendRouteObject()">Route to aboute component with state data</button> </div>`, styleUrls: ['./home.component.css'] }) export class HomeComponent { constructor(private router: Router) { } routeToHotelId(id: number) { this.router.navigate(['/hotels/' + id]); } sendRouteObject() { this.router.navigate(['/about'], { state: { frontEnd: JSON.stringify({ framwork: 'Angular', version: '9' }), site: 'edupala.com' } }); } }

Source: link

Recent Questions on angular

    Programming Languages