how to pass more than two parameters to modal ng2 bootstrap - javascript

I have to pass a flag in my Dialog Component. It must be like this
this.dialogService.addDialog(ModalDialogComponent, { title: 'History', message: this.comments, isHistoryModel:true});
My ModalDialogComponent:
export class ModalDialogComponent extends DialogComponent < ModalDialogModel, null > implements ModalDialogModel {
title: string;
message: any;
isHistoryModel: boolean;
constructor(dialogService: DialogService) {
super(dialogService);
}
}
Error snapshot:

You have to add
isHistoryModel:boolean
into your
ModalDialogModel

Related

Sequelize / Typescript: Types of parameters 'values' and 'values' are incompatible

I'm trying to create a BaseModel from which all my models are inherited.
I'm also trying to create a separate method() function that can get any of my models as argument.
This is my example code:
import {
Model, Optional
} from 'sequelize'; // v6.3.5
interface DefaultAttributes {
id: number;
}
interface TestAttributes extends DefaultAttributes {
field: number;
}
class BaseModel<T extends DefaultAttributes> extends Model<T, Optional<T, 'id'>> {
static test() {
}
}
class MyModel extends BaseModel<TestAttributes> {
}
function method<T extends typeof BaseModel>(model: T) {
model.test();
}
method(MyModel) // <<<<<< TypeScript ERROR
I've tried to do everything just as the documentation described. https://sequelize.org/master/manual/typescript.html
I'm getting the following TypeScript error:
TS2345: Argument of type 'typeof MyModel' is not assignable to parameter of type 'typeof BaseModel'.   Types of parameters 'values' and 'values' are incompatible.     Type 'Optional<T, "id">' is not assignable to type 'Optional<TestAttributes, "id">'.       Property 'field' is missing in type 'Optional<T, "id">' but required in type 'Pick<TestAttributes, "field">'.
Can pls someone help me what did I do wrong, or how can I create a method that can receive any UniqueModel inherited from BaseModel?
Try this:
import {
Model, Optional
} from 'sequelize'; // v6.3.5
interface DefaultAttributes {
id: number;
}
interface TestAttributes extends DefaultAttributes {
field: number;
}
class BaseModel<T extends DefaultAttributes> extends Model<T, Optional<T, 'id'>> {
static test() {
}
}
class MyModel extends BaseModel<TestAttributes> {
}
function method<T extends BaseModel>(model: T) {
model.test();
}
method(MyModel)

Angular 2 : ViewChild is undefined on parent

I have following error :
Error: Uncaught (in promise): TypeError: Cannot set property 'test_id' of undefined
TypeError: Cannot set property 'test_id' of undefined
The errror is trigger on this line:
console.log('after view init testList', this.productList.test_id);
I saw a lot of posts but all of them seems outdated and most of them are saying that I have to use a function ngAfterViewInit which I did.
I have a clic action that triggers updateTestId and I want to pass this id to my child view ProductListComponent.
Here is my parent component :
import { Component,ViewChild} from '#angular/core';
import {Test,TestData} from './testService';
import { LocalDataSource } from 'ng2-smart-table';
import {ProductListComponent} from '../../components/product/list/productList.component';
#Component({
selector: 'test-list',
templateUrl: './testList.html',
styleUrls: ['./testList.scss']
})
export class TestListComponent{
//tests: Test[];
tests: any[];
selected_test : number;
#ViewChild(ProductListComponent)
private productList: ProductListComponent;
constructor(protected service: TestData){
this.service.getData().then((data) => {
this.tests = data.tests;
this.source.load(data);
});
}
settings = {
editable : false,
actions: {
add:false,
edit:false,
delete:false
},
columns: {
id: {
title: 'ID',
type: 'number'
},
nb_cartons: {
title: 'Cartons',
type: 'number'
},
nb_items: {
title: 'Items',
type: 'number'
},
nb_pallets: {
title: 'Pallets',
type: 'number'
},
};
//source : Test[];
source: LocalDataSource = new LocalDataSource();
public updateTestId(value:any):void {
this.selected_test = value.data.id;
console.log('rowSelect', this.selected_test );
//console.log(this.productList.test_id)
}
}
And here is my child component :
import { Component,Input,Output, OnChanges, SimpleChanges } from '#angular/core';
import { LocalDataSource } from 'ng2-smart-table';
import {Test} from '../../test/testService';
#Component({
selector: 'product-list',
templateUrl: './productList.html',
styleUrls: ['./productList.scss']
})
export class ProductListComponent implements OnChanges{
#Input() test_id : number = null;
settings = {
editable : false,
actions: {
add:false,
edit:false,
delete:false
},
columns: {
id: {
title: 'ID',
type: 'number'
},
sku: {
title: 'SKU',
type: 'string'
},
reference: {
title: 'Reference',
type: 'string'
},
size: {
title: 'Size',
type: 'string'
},
},
edit: {
editButtonContent: '<i class="ion-edit"></i>',
saveButtonContent: '<i class="ion-checkmark"></i>',
cancelButtonContent: '<i class="ion-close"></i>',
}
};
source: LocalDataSource = new LocalDataSource();
constructor() {
}
ngOnChanges(changes: SimpleChanges) {
console.log(changes['test_id'],changes['test_id'].currentValue);
console.log('change in child',changes.test_id);
}
/*
#Input()
set _test_id(id: number) {
this._test_id = id;
}
get test_id(): number { return this._test_id; }
*/
}
i use the child selector like this :
<test-list></test-list>
<product-list #productList [test_id]="selected_test"></product-list>
Add a template reference variable name to the product-list in the template
<product-list #productList [test_id]="selected_test"></product-list>
And reference it by that in the component
#ViewChild('productList')
private productList: ProductListComponent;
EDIT:
In this case Vivek Doshi is correct in his answer that you don't need it since you are passing data to the child via #Input. But still - if you want to use ViewChild, this is a solution :)
If you want to pass data from parent to child you can directly pass
<product-list [test_id]="selected_test"></product-list>
That's it , nothing more.
There is no need to access it via #ViewChild
To detect the changed value over the time from product-list component
ngOnChanges(changes: SimpleChanges) {
console.log(changes['test_id'].currentValue);
}
Example :
#Component({selector: 'my-cmp', template: `...`})
class MyComponent implements OnChanges {
#Input()
prop: number;
ngOnChanges(changes: SimpleChanges) {
// changes.prop contains the old and the new value...
}
}
Things to note :
You need to implements OnChanges on child component.
For more detail please read this doc

Cannot find namespace error for model in Angular2/TypeScript

The FeaturedCategories model
export class FeaturedCategories {
categories: Array<{ id: number, title: string, graphic: string, categorycards: Array<{}> }>;
}
Also tried this:
export class FeaturedCategories {
id: number;
title: string;
graphic: string;
categorycards: Object[];
}
The Component
import { Component, ChangeDetectionStrategy, ViewEncapsulation } from '#angular/core';
import { ApiService } from '../shared/services/api.service';
import { FeaturedCategories } from '../shared/models/home/featuredcategories';
#Component({
changeDetection: ChangeDetectionStrategy.Default,
encapsulation: ViewEncapsulation.Emulated,
selector: 'home',
styleUrls: [ './home.component.css' ],
templateUrl: './home.component.html'
})
export class HomeComponent {
testFeaturedCategories: Array<FeaturedCategories>;
constructor(private api: ApiService) {
// we need the data synchronously for the client to set the server response
// we create another method so we have more control for testing
this.universalInit();
}
universalInit() {
console.log('universalInit...')
this.api.getFeatured()
.subscribe(categories => {
console.log('categories', categories);
this.testFeaturedCategories = categories
});
}
}
This will work: testFeaturedCategories: Array<{}>;
However I'm trying to use TypeScript to let my App know what type of model to expect.
This causes the error above:
testFeaturedCategories: FeaturedCategories.categories;
And if I just try this: testFeaturedCategories: FeaturedCategories;
I get a type [{}] is not assignable error.
UPDATE
So I noticed that when I commented out all the keys in my FeaturedCategories model finally the error goes away and
featuredCategories: FeaturedCategories[]; will work.
However now this is just an empty object without keys to expect :(
export class FeaturedCategories {
// id: number;
// title: string;
// graphic: string;
// categorycards: Object[];
}
this is working fine for me.
export class MyComponent {
categories: FeaturedCategories[] = [{
id: 1,
title: "",
graphic: "",
categorycards: [{}]
}];
}
export class FeaturedCategories{
id: number;
title: string;
graphic: string;
categorycards: Object[];
}
My problem was trying to type my Array, instead of just using the Typed objects that exist in the larger Array.
Also had a problem in my service, originally I had this:
/**
* Get featured categories data for homepage
* /wiki
*/
getFeatured(): Observable<[{}]> {
return this.http.get(`${this.getFeaturedUrl}/home`)
// .do(res => console.log('getFeatured res', res.json()))
.map(res => res.json())
.catch(this.handleError);
}
I did not need or could even use a type for my larger Categories array, what I needed was a smaller type for the exact Objects that exist in that larger Array:
export class FeaturedCategory {
id?: number;
type: string;
title: string;
graphic?: string;
video?: string;
categorycards: Array<{}>;
}
So now with the correct Type of Objects inside my Array I added it to the service:
getFeatured(): Observable<[FeaturedCategory]> {
return this.http.get(`${this.getFeaturedUrl}/home`)
.map(res => res.json())
.catch(this.handleError);
}
Now back in my Component I imported the single Typed Object
import { FeaturedCategory } from '../shared/models/home/featuredcategory';
Then typed the variable:
featuredCategories: Array<FeaturedCategory>;
And finally in ngOnInit
ngOnInit() {
this.api.getFeatured()
.subscribe(categories => {
console.log('categories', categories);
this.featuredCategories = categories;
});
}
No more errors :)

Angular2 - Share component controllers

I have two page components that use the same methods with the exception of using two different type classes. The two components are called Services and Users. Both components use templates that are very similar with the exception of the class property info it displays. It seems to be inefficient to repeat methods on both controllers, is there a way to combine/share controllers.
Services.ts
import { Component } from '#angular/core';
import { CORE_DIRECTIVES } from '#angular/common';
const template = require('./service.component.html');
const style = require('./service.component.css');
interface Service {
id: number;
name: string;
summary: string;
path: string;
};
#Component({
selector: 'admin-services',
directives: [ CORE_DIRECTIVES],
template: template,
styles: [ style ]
})
export class ServiceComponent {
services = Services;
selectedService:Service ;
constructor() {
}
onselect(service:Service){
this.selectedService = service ;
}
onEdit(service:Service){
console.log("Edit: "+service);
}
onDelete(service:Service){
console.log("Delete: "+service);
}
onView(service:Service){
console.log("View: "+service);
}
onAdd(){
this.selectedService = <Service>{};
}
}
User.ts
import { Component } from '#angular/core';
import { CORE_DIRECTIVES } from '#angular/common';
const template = require('./users.component.html');
const style = require('./users.component.css');
interface User {
id: number;
image: string;
name: string;
email: string;
role: string;
};
#Component({
selector: 'admin-users',
directives: [ CORE_DIRECTIVES],
template: template,
styles: [ style ]
})
export class UsersComponent {
users = Users;
selectedUser:User ;
constructor() {
}
onselect(user:User){
this.selectedUser = user ;
}
onEdit(user:User){
console.log("Edit: "+user);
}
onDelete(user:User){
console.log("Delete: "+user);
}
onView(user:User){
console.log("View: "+user);
}
onAdd(){
this.selectedUser = <User>{};
}
}
Yep, this is where Angular's component-driven design and Typescripts's class-driven design really shine:
Having defined a ServicesComponent as you have above, you can simply extend that class and attach different component metadata to it:
#Component({
selector: 'admin-users',
directives: [ CORE_DIRECTIVES],
template: template,
styles: [ style ]
})
export class UsersComponent extends ServicesComponent {
constructor(){
super();
}
//override whatever methods/fields in the parent class you need to (and only those)
}
I believe you can create a service with a single set of methods and pass in an object. Then cast the object to the desired class and use it in the method.

Typescript compiler error expected semi-colon with Angular 1.5 component

I am getting an expected semi-colon error from TypeScript when trying to compile the following Angular component.
It seems fine to me but the error was only thrown when i added the this.$routeConfig array:
export class AppComponent implements ng.IComponentOptions {
public template: string;
public $routeConfig: Array<any>;
constructor(){
this.template = `<h1>Home</h1>
<ng-outlet></ng-outlet>`;
this.$routeConfig: [{
path: '/',
component: 'loginComponent',
name: 'Login',
useAsDefault: true
}];
}
}
Just realised my 'school boy' error!
Should be this.$routeConfig = [];

Categories

Resources