logo
down
shadow

angular 4 reusable component and template


angular 4 reusable component and template

By : SteveK
Date : October 18 2020, 01:08 AM
Hope this helps I figured it out myself. In fact, the solution is rather trivial. My mistake was to try two things at once in my report.component, providing a template as well as logic. What I ended up is an abstract component that holds the logic and is extended by each report, as well as several smaller components for the similar parts in each report (shell, result list, etc.). I also switched from template forms to reactive forms.
report-base.component.ts holds the common logic
code :
import {OnInit} from '@angular/core';
import {FormBuilder, FormGroup} from '@angular/forms';
import {MatPaginator, MatSidenav} from '@angular/material';

import 'rxjs/add/operator/map';

import {ReportsDataSource} from '../common/services/reports-datasource.service';
import {ReportsService} from '../common/services/reports.service';
import {ReportsResultlistService} from '../common/services/reports-resultlist.service';

export abstract class ReportBaseComponent implements OnInit {
    constructor(
        protected _formBuilder: FormBuilder, protected _reportService: ReportsService, protected _resultlistService: ReportsResultlistService) {
    }


    /**
     * For toggling the search form and resultlist action buttons
     * @type {boolean}
     */
    protected hasResults = false;

    /** Default data source for the table */
    protected dataSource: ReportsDataSource;

    /** search form controls */
    protected searchForm: FormGroup;

    /** result table columns */
    protected columns = [];

    ngOnInit() {
        this.createForm();
        this.dataSource = new ReportsDataSource(this._reportService, this._resultlistService);
    }

    /**
     * Builds the searchForm Group
     */
    protected createForm() {
        // create an empty form
        this.searchForm = this._formBuilder.group({});
    }

    /**
     * Submits the form/loads data (f.ex. pagination)
     */
    protected getData() {
        this.hasResults = true;
        this.dataSource.search = this.searchForm.value;
        this.dataSource.getData();
    }
}
import {Component, Input} from '@angular/core';
import {ActivatedRoute} from '@angular/router';

@Component({
    selector: 'app-report-shell',
    templateUrl: './report-shell.component.html',
})
export class ReportShellComponent {
    constructor(private route: ActivatedRoute) {
        this.title = route.routeConfig.data['caption'];
    }

    @Input() hasResults = false;
    title: string;
}
<mat-expansion-panel [expanded]="!hasResults">
    <mat-expansion-panel-header>
        Search
    </mat-expansion-panel-header>
    <ng-content select="form"></ng-content>
</mat-expansion-panel>
<div class="result-list">
    <mat-toolbar class="result-header"><span>{{ title }}</span>
        <span class="fill-remaining-space"></span>
        <button class="fa fa-file-excel-o" (click)="exportExcel()"></button>
    </mat-toolbar>
    <ng-content select=".result-table"></ng-content>
</div>
import {Component, OnInit} from '@angular/core';
import {FormBuilder, Validators} from '@angular/forms';

import {ReportChildreportService} from './childreport.service';
import {ReportsDataSource} from '../../common/services/reports-datasource.service';
import {ReportsResultlistService} from '../../common/services/reports-resultlist.service';

import {ReportBaseComponent} from '../report-base.component';


@Component({
    selector: 'app-report-dispatches',
    templateUrl: './dispatches.component.html',
    providers: [ReportChildreportService, ReportsResultlistService, ReportsDataSource]
})
export class ReportDispatchesComponent extends ReportBaseComponent implements OnInit {
    constructor(protected _reportService: ReportChildreportService, protected _formBuilder: FormBuilder, protected _resultlistService: ReportsResultlistService) {
        super(_formBuilder, _reportService, _resultlistService);
    }

    /** result table columns */
    columns = [
        {columnDef: 'name', header: 'Name', cell: (row) => `${row.name}`}
    ];

    createForm() {
        this.searchForm = this._formBuilder.group({
            name: ''
        });
    }
}
<app-report-shell [hasResults]="hasResults">
    <form (ngSubmit)="getData()" [formGroup]="searchForm" novalidate>
                    <mat-form-field>
                        <input matInput placeholder="search for a name" name="name" formControlName="name">
                        <mat-error>Invalid name</mat-error>
                    </mat-form-field>
                </div>
        </div>
        <app-form-buttons [status]="searchForm.status"></app-form-buttons>
    </form>
        <app-report-result-list
                [(dataSource)]="dataSource"
                [columns]="columns"
                [displayedColumns]="displayedColumns"
                class="result-table"
        ></app-report-result-list>    
</app-report-shell>


Share : facebook icon twitter icon
When use a directive or reusable component on Angular 2 or Angular 4?

When use a directive or reusable component on Angular 2 or Angular 4?


By : 심지현
Date : March 29 2020, 07:55 AM
around this issue I have this following code: , One option is to use a component and you can do that this way:
code :
import { Component } from '@angular/core';

@Component({
    selector: 'popover',
    template: `
      <popover-content #myPopover title="Selector de colores" [closeOnClickOutside]="true">
          <div class="color-palette blue1" (click)="onSetColor('blue1')" style="cursor:pointer"></div>
          ...
          <div class="color-palette violet3" (click)="onSetColor('violet3')" style="cursor:pointer"></div>              
      </popover-content>
    `
})
export class PopoverComponent {
  @Output() setcolor: EventEmitter<string> = new EventEmitter<string>();

  constructor() { }

  onSetColor(color: string) {
    this.setColor.emit(color);
  }
}
<popover (setColor)="onSetColor($event)"></popover>
How do I get the id of a form input element for a label in a reusable Angular component template?

How do I get the id of a form input element for a label in a reusable Angular component template?


By : carnifex.iulius
Date : March 29 2020, 07:55 AM
should help you out One way is to use the @Input decorator and pass values from parent where you have the component to the child component where your form or lable is
parentcomponent
code :
<myComponent idToUse="id1"></myComponent>
<myComponent idToUse="id2"></myComponent>
@Component({
selector : "myComponent",
template: `<div>
    <label for="{{idToUse}}">Name</label>
    <input [(ngModel)]="name" type="text" id="{{idToUse}}"/>
</div>`
})
export class childComponent {
@Input() idToUse;
}
Is @Component+router-outlet the only way to have reusable template in Angular 7?

Is @Component+router-outlet the only way to have reusable template in Angular 7?


By : Camille Agustin Faja
Date : March 29 2020, 07:55 AM
Hope this helps I'm not sure of your exact requirements, but it sounds like you should not be using router outlets in this situation.
Router outlets are meant for when a "parent" component has several "child" components, and would like to show one at a time, and the one that it shows depends on the route.
code :
<section class="landing-search">
    <router-outlet name="search-bar">
<section>
<section class="landing-search">
    <landing-search-bar></landing-search-bar>
<section>
Reusable component with Angular

Reusable component with Angular


By : user3182326
Date : March 29 2020, 07:55 AM
I hope this helps you . You need to create a library then you can deploy it to NPM and consume it in different projects. Another solution is using polymer, you create your web component and deploy it to NPM and it can be used by different technologies like Angular, JS, React etc. web components are more generic than a angular library.
https://blog.angularindepth.com/creating-a-library-in-angular-6-87799552e7e5
How to make an angular component reusable? (Angular 2+)

How to make an angular component reusable? (Angular 2+)


By : Martinspire
Date : March 29 2020, 07:55 AM
I hope this helps you . I've built a few controls similar to yours by leveraging ControlValueAccessor and NG_VALUE_ACCESSOR from angular forms. Basically, these provide you with a pattern to build your own custom and reusable form controls.
Below is an example code but you can also follow this tutorial to get your component built.
code :
import { Component, OnInit, forwardRef } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR, NG_VALIDATORS, FormControl } from '@angular/forms';

const IP_VALUE_ACCESSOR: any = {
    provide: NG_VALUE_ACCESSOR,
    useExisting: forwardRef(() => IpInputComponent),
    multi: true
};

@Component({
  selector: 'ip-address-input',
  providers: [IP_VALUE_ACCESSOR],
  templateUrl: './ip-input.component.html',
  styleUrls: ['./ip-input.component.css']
})
export class IpInputComponent implements OnInit, ControlValueAccessor {

ipBlock1: string;
ipBlock2: string;
ipBlock3: string;
ipBlock4: string;
ipBlock5: string;

    disabled: boolean;
    onChange: Function; 
    onTouched: Function; 

    get value(): string {
        return ipBlock1 + '.' + ipBlock2 + '.' + ipBlock3 + '.' + ipBlock4 + ':' + ipBlock5;
    }

    constructor() {
        this.onChange = (_: any) => {};
        this.onTouched = () => {};
        this.disabled = false;
    }

    ngOnInit() {
    }

    writeValue(obj: any): void {
        if(obj) {
            let arr = obj.split('.');

            this.ipBlock1 = arr[0];
            this.ipBlock2 = arr[1];
            this.ipBlock3 = arr[2];
            this.ipBlock4 = arr[3].split(':')[0];
            this.ipBlock5 = arr[3].split(':')[1];
        }
    }

    registerOnChange(fn: any): void {
        this.onChange = fn;
    }
    registerOnTouched(fn: any): void {
        this.onTouched = fn;
    }
    setDisabledState?(isDisabled: boolean): void {
        this.disabled = isDisabled;
    }
}
<div class="form-inline" style="display: inline-block">
  <input required class="form-control" type="number" [ngModel]="ipBlock1" />. 
  <input required class="form-control" type="number" [ngModel]="ipBlock2" />.
  <input required class="form-control" type="number" [ngModel]="ipBlock3" />.
  <input required class="form-control" type="number" [ngModel]="ipBlock4" />:
  <input required class="form-control" type="number" [ngModel]="ipBlock5" />
</div>
<ip-address-input formControlName="ipAddress" (value)="ipAddress.value"></ip-address-input>
Related Posts Related Posts :
  • How to access the static variable in ngFor in angular2
  • Angular2 ngModelChange previous value
  • Angular 2: Form containing child component
  • What is the difference between formControlName and FormControl?
  • Angular 2 route is getting loaded into the top level router-outlet despite having a specified router-outlet defined on t
  • Angular2 with matrix url notation
  • RxJS Refactor nested map statement
  • Angular - *ngFor not showing data
  • Typescript Error: Type 'any' is not a constructor function type
  • Angular2 - getting a TemplateRef inside a service
  • Integrating Angular Universal into existing CLI Applications
  • Why even use sessionStorage in Angular?
  • Why does [disabled]="canDisable" will not work for Angular2 reactive forms
  • Style backgroundColor p-fileUpload primeNG
  • Angular4 Dependency Injection: what am I doing wrong?
  • Appending string to img src in angular 4
  • how to open ng bootstrap modals from another component?
  • angular2 transition animation is not working
  • AdminLTE - data-widget="tree" - Open menu by default
  • How to implement one interface in an other
  • Executing resolvers one after the other in Angular 2+
  • Login redirect a user with Azure AD B2C from an Angular application and msal.js
  • add button into google maps Angular2
  • Integrating Firebase admin with Angular 4 project
  • Calling services in the correct order in Angular 4?
  • Angular 2: How to handle http oauth authtoken 401 errors on a global basis
  • Implement Validators.required in a custom component
  • Testing an async injectable service
  • How to change angular 4 property on click event?
  • Angular 4 - Lazy Loading routes doesn't work
  • Angular - Filter ngFor data array of objects
  • How to get current authenticated user angularfire2 (angular) so that it is usable in time for class methods?
  • data passed with resolve(x) is received as undefined
  • Can't get local storage value on initial page load
  • Angular 2 Route Aliases
  • Tslint - type trivially inferred - Why is it bad practice to include the type here?
  • Angular 4 "Property does not exist on type component"
  • Uncaught Error: Unexpected value 'SharedModule' imported by the module 'AppModule'. Please add a @NgModule annotation
  • Connecting angular to firebase using angularFire2 version 5.0
  • Angular 4 Timer up ticking too fast
  • How to do form validation for a select box?
  • Access async object param into child component in Angular 4
  • Ionic How to implement pressing,release,drag,drop event of button?
  • Angular not pulling data through Angularfire2
  • How to set a value from observable to a variable in Angular 2
  • Get Grand Total From Rows Total
  • Angular - Does importing unnecessary ngModules increase file size if they have been imported elsewhere?
  • Capture requests globally in angular 4 and stop if no internet
  • How to return the promise then()/catch() result to the function containing the promise?
  • Using third party libraries (MxGraph) in angular 4, without installing them from npm
  • Angular: Run canActivate on each route change
  • angular: how to loop for numbers?
  • Preventing a Pyramid of Doom using rxjs .subscribe with Angular - flattening the number of .subscribes
  • Angular 4 Http Chain Requests
  • Obtaining references to all directives of a certain type up the component tree
  • using third party library in angular
  • How to access to an ngModel element inside a reusable component
  • Angular 2 change sidenav content depending on the current router state
  • How to retrieve the data only if the subscride processing is completed
  • Angular 2 transfer variable from one template to another
  • shadow
    Privacy Policy - Terms - Contact Us © soohba.com