Angular 2 Directive and FormGroup: to change all input text to uppercase - angular2-directives

Please help. I'm having trouble creating a generic directive that will always set all the inputs type text to uppercase.
below is my directive:
import { Directive, ElementRef, HostListener } from '#angular/core';
import { NgControl } from "#angular/forms";
#Directive({
selector: 'input[type="text"]:not(.none-transform)',
host:{
'(input)':'format($event)'
}
})
export class TextUppercase {
constructor(private _el: ElementRef, private _control? : NgControl) {
}
format(value) {
let uppercase = this._el.nativeElement.value.toUpperCase();
this._control.control.setValue(uppercase);
}
}
When I didn't set the formControl in my form, this error come:
ERROR Error: Uncaught (in promise): Error: No provider for NgControl!
Error: No provider for NgControl!
How to make the directive still working even the formControl is not set?

Related

How to create directive for disable input in reactive form with Angular 8^?

The old directive from angular 6 doesn't working more.
(I need directive and not sample code in the component because of the need for dynamism that changes during the run.
this is the old directive code:
import { Directive, Input } from "#angular/core";
import { NgControl } from "#angular/forms";
#Directive({
selector: "([formControlName], [formControl])[disabledControl]"
})
export class DisabledControlDirective {
#Input() set disabledControl(state: boolean) {
const action = state ? "disable" : "enable";
this.ngControl.control[action]();
}
constructor(private readonly ngControl: NgControl) {}
}

How to install Express middleware (express-openapi-validator) in NestJS?

I am writing a NestJS application. Now I want to install the Express middleware express-openapi-validator.
However, I can't get it to work. There is a description for how to install the express-openapi-validator in express, but it always results in errors.
For example
export class AppModule implements NestModule {
configure(consumer: MiddlewareConsumer) {
consumer.apply(middleware({apiSpec "./bff-api.yaml"}))
.forRoutes(OrganizationController)
}
}
results in
error TS2345: Argument of type 'OpenApiRequestHandler[]' is not assignable to parameter of type 'Function | Type<any>'.
Type 'OpenApiRequestHandler[]' is missing the following properties from type 'Type<any>': apply, call, bind, prototype, and 4 more.
How can I install this middleware in NestJS?
I added a NestJS example to express-openapi-validator (static link for posterity).
The AppModule looks basically identical, although you don't need to iterate over the middlewares:
#Module({
imports: [PingModule],
providers: [{ provide: APP_FILTER, useClass: OpenApiExceptionFilter }],
})
export class AppModule implements NestModule {
configure(consumer: MiddlewareConsumer) {
consumer
.apply(
...OpenApiValidator.middleware({
apiSpec: join(__dirname, './api.yaml'),
}),
)
.forRoutes('*');
}
}
I also added an exception filter to convert the error from express-openapi-validator to a proper response; otherwise I would always get a 500 error. You could also use this approach to convert the error into a custom error format.
import { ArgumentsHost, Catch, ExceptionFilter } from '#nestjs/common';
import { Response } from 'express';
import { error } from 'express-openapi-validator';
#Catch(...Object.values(error))
export class OpenApiExceptionFilter implements ExceptionFilter {
catch(error: ValidationError, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const response = ctx.getResponse<Response>();
response.status(error.status).json(error);
}
}
interface ValidationError {
status: number;
message: string;
errors: Array<{
path: string;
message: string;
error_code?: string;
}>;
path?: string;
name: string;
}
I have now got it working:
configure(consumer: MiddlewareConsumer) {
middleware({
apiSpec: `${__dirname}/../api-doc/bff-api.yaml`
}).forEach(value => consumer.apply(value).forRoutes(OrganizationController))
}

How to susbscribe to property on the state in Vue?

I have vue application.
I'm using vuex and vuex-class packages to connect with the store.
in my component(vue-property-decorator) I want to subscribe to some property on the state, and when it change then I want to know.
for example:
my state for example:
const state = {
error: null,
};
and getters:
const getters = {
error(state: any) {
return state.error;
},
};
my component:
import { Component } from 'vue-property-decorator';
import { namespace } from 'vuex-class';
const SomeModule = namespace('somemodule');
#Component({})
export default class MyPage extends SomeBaseComponent {
#SomeModule.Getter('error')
error: any;
// HOW TO know when error has change?
}
onErrorChanged() {
//?????
}
I want onErrorChanged will fire every time the error property on the state changed.
How to do that?
I'm a maintainer of vue-property-docorator. Thanks for using the library.
If you'd like to observe the changes of error property, you can do it by $watch.
As you are using vue-property-decorator, #Watch decorator is available.
#Component({})
export default class MyPage extends SomeBaseComponent {
#SomeModule.Getter('error')
error: any;
#Watch('error')
onErrorChanged(newErrorVal, oldErrorVal) { }
}

Angular2 ng-book-2 simple sample chapter 1 app , it works fine in the browser , but why do I get this error?

On Mac OS X El Capitan, I follow all the steps from Page 1 to page 18 of this simple app, but at the screen where I run "ng serve" I get this error:
ERROR in [default]
/Users/bob/angular2_hello_world/src/app/user-item/user-item.component.ts:11:8
Property 'name' does not exist on type 'UserItemComponent'.
From Page 1 :
Writing your First Angular 2 Web Application
Simple Reddit Clone
TO
Page 18:
Try it out
"After making these changes reload the page and the page should display Hello Felipe""
The error is that you use a "name" variable inside the component template but it's not defined inside the component. Define and use it like this in your component:
import { Component } from '#angular/core';
#Component({
selector: 'app-user-item-component',
template: `
<h1>{{name}}</h1>
`,
styles: []
})
export class AppComponent {
name: string = "Hello Felipe"
}
I had the same problem, just reading ng-book2-r49, you need to define that name property in class as names: string[]; so it looks like this
import { Component, OnInit } from '#angular/core';
#Component({
selector: 'app-user-item',
templateUrl: './user-item.component.html',
styleUrls: ['./user-item.component.css']
})
export class UserItemComponent implements OnInit {
name: string;
constructor() {
this.name = 'Felipe'; // set the name
}
ngOnInit() {
}
}

defining providers for an angular2 component using dart

I'm writing an angular2 dart application using Intellij.
I created a provider called Auth that should be injected to the app component.
I defined the Auth service using the following code:
import 'package:angular2/core.dart';
import 'package:auth0_lock/auth0_lock.dart';
import './config.dart';
#Injectable()
class Auth {
Auth0Lock lock;
Auth() {
this.lock = new Auth0Lock(configObj.auth0.apiKey, configObj.auth0.domain);
}
updateProfileName(data) {
var profile = data['profile'] != null ? data['profile'] : data;
print(profile['name']);
}
login() {
this.lock.show(popupMode: true, options: {'authParams': {'scope': 'openid profile'}}).then(this.updateProfileName);
}
}
and the app component using the following code:
import 'package:angular2/core.dart';
import 'package:angular2/router.dart';
import 'welcome_component.dart';
import 'auth_service.dart';
#Component(
selector: 'my-app',
templateUrl: '/www/my-app.html',
providers: [Auth]
)
#RouteConfig(const [
const Route(path: '/welcome', component: WelcomeComponent, name: 'welcome')
])
class AppComponent {
Auth auth;
AppComponent(Auth auth) {
this.auth=auth;
}
}
now intellij is complaning about the providers array with the error message arguments of constant creation must be constant expressions.
I'm new to dart... but if the Component configuration needs consts, how can I provide classes to be used there ?
thanks
Just adding const should do:
providers: const [Auth]
The error you're seeing is because [Auth] creates a List that — although it contains only a const memeber — is itself not constant. (For example, it could be added to, or cleared.) Dart requires you to specify explicitly that the List is constant.