Angular_JS_Complete_Document
Angular_JS_Complete_Document
Example Implementation:
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const authToken = localStorage.getItem('authToken');
const modifiedReq = req.clone({
headers: req.headers.set('Authorization', `Bearer ${authToken}`)
});
return next.handle(modifiedReq);
}
}
providers: [
{ provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true }
]
What is RxJS?
RxJS (Reactive Extensions for JavaScript) is a library for composing asynchronous and
event-based programs using observable sequences. It provides tools to work with streams
of data.
Example Usage:
Example:
@Component({
selector: 'app-example',
template: `
<div #viewChildDiv>View Child Example</div>
<ng-content></ng-content>
`
})
export class ExampleComponent {
@ViewChild('viewChildDiv') viewChildDiv: ElementRef;
@ContentChild('contentChildDiv') contentChildDiv: ElementRef;
ngAfterViewInit() {
console.log(this.viewChildDiv.nativeElement.innerText);
console.log(this.contentChildDiv.nativeElement.innerText);
}
}
Example:
@Injectable()
export class AuthGuard implements CanActivate {
canActivate(): boolean {
const isLoggedIn = !!localStorage.getItem('authToken');
return isLoggedIn;
}
}
Route Configuration:
Example:
@Injectable()
export class ApiService {
fetchData() {
return 'Data fetched!';
}
}
@Component({
selector: 'app-root',
template: '{{ data }}'
})
export class AppComponent {
data: string;
constructor(private apiService: ApiService) {
this.data = this.apiService.fetchData();
}
}
JavaScript Questions
Parent Component:
@Component({
selector: 'app-root',
template: `<app-auth-form (formSubmitted)="onFormSubmitted($event)"></app-auth-
form>`
})
export class AppComponent {
onFormSubmitted(data: any) {
console.log('Form Data:', data);
// API call logic
}
}
Child Component:
<form (ngSubmit)="submitForm()">
<input [(ngModel)]="formData.username" name="username" placeholder="Username" />
<input [(ngModel)]="formData.password" name="password" placeholder="Password"
type="password" />
<button type="submit">Submit</button>
</form>
@Component({
selector: 'app-auth-form',
templateUrl: './auth-form.component.html'
})
export class AuthFormComponent {
@Output() formSubmitted = new EventEmitter<any>();
formData = { username: '', password: '' };
submitForm() {
this.formSubmitted.emit(this.formData);
}
}