Adding styles to child Components in Angular2-RC5 - css

I have an angular2 app with an RC5 style submodule. The module is my tutorial module, with tutorial.component as it's root component.
#Component({
selector: 'tutorial',
template: `
<div class="content row">
<div class="col s9">
<h1>Tutorial</h1>
<router-outlet></router-outlet>
</div>
</div>`,
styleUrls: ['./app/tutorial/tutorial.css'],
directives: [ROUTER_DIRECTIVES],
encapsulation: ViewEncapsulation.None
})
export class tutorialComponent {
public chapters = _chapters;
clickedItem: number = 0;
}
Here you can see the module routes:
const tutorialRoutes: Routes = [
{
path: 'tutorial',
component: tutorialComponent,
children: [
{ path: 'chapter/:id', component: chapterComponent },
{ path: '', redirectTo: 'chapter/0', pathMatch: 'full'},
]
}
];
So that's fine, however, in my child Component, chapterComponent, my css isn't being applied. Here is the component:
#Component({
selector: 'chapter',
template: `<div [innerHTML]="content"></div>`,
styleUrls: ['./app/tutorial/chapter/chapter.css']
})
export class chapterComponent implements OnInit, OnDestroy {
private sub: Subscription;
private content: string = '';
constructor( private route: ActivatedRoute) { }
ngOnInit() {
this.sub = this.route.params.subscribe(params => {
var id: string = params['id'];
this.content = id;
var that = this;
var _url = './chapter/' + params['id'] + '.html';
$.ajax({
url: _url,
success: function (result) {
that.content = result;
}
});
});
}
}
But if I use the exact same path to the chapter.css file in my tutorial component, then the styles are applied.
Why are my child components behaving differently to parent components with respect to css application.

Related

Import component dynamically in vue 3

I want to import screens based on user id. I created a wrapper component to do this but It doesn't work for nested routes. In vue 2 I can use app instance in router to decide which screen renders but vue 3 I can't do this approach
<script>
//imports
export default {
setup() {
const decidedComponent = ref();
const { user } = useAuth();
const route = useRoute();
function decide() {
decidedComponent.value = markRaw(
defineAsyncComponent(() =>
user.id === 1
? import(`#/screens/1/${route.meta.name}/index.vue`)
: user.id === 2
? route.meta.name
: import(`#/screens/2/${route.meta.name}/index.vue`)
)
);
}
return {
decide,
decidedComponent,
};
},
beforeRouteEnter(to, from, next) {
// When first entering the route
next((vm) => vm.decide());
},
};
</script>
<template>
<component
v-if="decidedComponent"
:is="decidedComponent"
:key="`${decidedComponent.__file}`"
></component>
</template>
//router
{
path: "/customer/:customerId",
name: "customer",
component: DecideComponent,
meta: {
name: "MultiPages",
},
children: [
{
path: "details",
name: "customer.details",
component: DecideComponent,
meta: {
name: "CustomerDetails",
},
},
It doesn't work for parent route.

Vue3 - Routes if page doesn't exist with dynamic routes not working with my 404?

I am using Vue3 and have my Router setup for detail pages. Any title returns the same data and 404 is being ignored even after adding the regEx inside the routes.
Routes:
import { createRouter, createWebHistory, RouteRecordRaw } from "vue-router";
import HomeView from "../views/HomeView.vue";
import ErrorView from "../views/ErrorView.vue";
const routes: Array<RouteRecordRaw> = [
{
path: "/",
name: "home",
component: HomeView,
},
{
path: "/about",
name: "about",
// route level code-splitting
// this generates a separate chunk (about.[hash].js) for this route
// which is lazy-loaded when the route is visited.
component: () =>
import(/* webpackChunkName: "about" */ "../views/AboutView.vue"),
},
{
path: "/article/:slug",
name: "article",
component: () =>
import(/* webpackChunkName: "article" */ "../views/ArticleView.vue"),
},
{
path: "/404",
name: "PageNotExist",
component: () => import("../views/ErrorView.vue"),
},
{
path: "/:catchAll(.*)", // Unrecognized path automatically matches 404
redirect: "/404",
},
];
const router = createRouter({
history: createWebHistory(process.env.BASE_URL),
routes,
});
export default router;
Article:
<template>
<div>
<h1>{{ data.title }}</h1>
<h3>{{ data.textarea }}</h3>
</div>
</template>
<script lang="ts">
import { useSanityFetcher } from "vue-sanity";
import { defineComponent } from "vue";
export default defineComponent({
name: "ArticleView",
setup: () => {
const articleQuery = `*[_type == "article"][0] {
title,
textarea,
}`;
const options = {
listen: true,
clientOnly: true,
};
const { data } = useSanityFetcher<object>(articleQuery, options);
return { data };
},
});
</script>

Give class to dynamically created button in angular

I am creating a button and assigning class in component.ts. Style of css does not apply on the button (button font color doest not change). Code of component.ts is
let button = document.createElement('button');
button.innerHTML = 'North';
button.setAttribute('class', 'btn');
let element = document.createElement('div');
element.appendChild(button);
and component.css is
.btn
{
color: red;
}
please try this
button.classList.add("btn");
Use angular components for create buttons
#Component({
selector: 'my-app',
templateUrl: '',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
#ViewChild('element', { read: ViewContainerRef }) container: ViewContainerRef;
constructor(
private _componentFactoryResolver: ComponentFactoryResolver,
private _injector: Injector,
) {}
addButton(): void {
const [componentRef, componentInstance] = this._createButton();
componentInstance.title = 'North'
componentInstance.class = 'active'
this.container.insert(componentRef.hostView);
}
private _createButton(): [ComponentRef<ButtonComponent>, ButtonComponent] {
const componentFactory = this._componentFactoryResolver.resolveComponentFactory(ButtonComponent);
const componentRef = componentFactory.create(this._injector)
const componentInstance = componentRef.instance;
return [componentRef ,componentInstance];
}
}
button component
#Component({
selector: 'app-button',
templateUrl: './button.component.html',
styleUrls: ['./button.component.css'],
})
export class ButtonComponent {
#Input() title: string;
#Input() class: string = '';
}
I put the whole example on stackblitz

Angular 8 - formControlName inside Kendo TextArea component

I am trying to use formControlName inside a Kendo Text Area, and have a outer component apply it.
Using the following code base link, its still not working.
Angular 2 - formControlName inside component
How would someone fix this?
InputText.ts
export class InputTextComponent implements AfterViewInit, ControlValueAccessor {
#Input() disabled: boolean;
#Output() saveValue = new EventEmitter();
value: string;
onChange: () => void;
onTouched: () => void;
writeValue(value: any) {
this.value = value ? value : "";
}
registerOnChange(fn: any) {this.onChange = fn}
registerOnTouched(fn: any) {this.onTouched = fn}
setDisabledState(isDisabled) {this.disabled = isDisabled}
}
InputText.html
<input kendoTextBox />
Not sure this is what you are asking but in order to use formControlName inside a custom component here is what you do
app.module.ts
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { AppComponent } from './app.component';
import { FormsModule, ReactiveFormsModule } from '#angular/forms';
import { InputTextComponent } from './input-text';
#NgModule({
declarations: [
AppComponent,
InputTextComponent
],
imports: [
FormsModule,
ReactiveFormsModule,
BrowserModule,
],
bootstrap: [AppComponent]
})
export class AppModule { }
app.component.html
<form [formGroup]="details">
<input-text formControlName="name"></input-text>
<!-- This should show the name as you change it in your custom control -->
{{details.value | json}}
</form>
app.component.ts
import { Component } from '#angular/core';
import { FormGroup, FormControl } from '#angular/forms';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
public details: FormGroup;
constructor(
) {
this.details = new FormGroup({
name: new FormControl("name")
});
}
}
input-text.component.html
<input kendoTextBox [(ngModel)]="value" (ngModelChange)="onChange($event)" />
input-text.component.ts
import { Component, forwardRef } from "#angular/core";
import { NG_VALUE_ACCESSOR, ControlValueAccessor } from "#angular/forms";
#Component({
selector: "input-text",
templateUrl: "./input-text.html",
styleUrls: ["./input-text.scss"],
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => InputTextComponent),
multi: true
}
]
})
export class InputTextComponent implements ControlValueAccessor {
public value: string;
propagateChange = (value: string) => {};
writeValue(obj: any): void {
this.value = obj;
}
registerOnTouched(fn: any): void {}
registerOnChange(fn) {
this.propagateChange = fn;
}
onChange(newValue){
this.propagateChange(newValue);
}
}

What am I missing so I can use the router on Nativescript?

I am attempting to build my first ever app using nativescript. I am going through the docs but not sure what I'm missing so I can't fix it.
I have the following structure:
- app
-- app-routing.module.ts
-- app.component.html
-- app.component.ts
-- app.css
-- app.module.ts
- home
-- home.component.css
-- home.component.html
-- home.component.ts
- restaurant
-- restaurant.component.css
-- restaurant.component.html
-- restaurant.component.ts
The thing is, I am trying to make it so that when someone taps on an element in the home.component.html:
<Image class="h3 m-5" col="0" row="0" src="~/images/beet-logo.jpg" (tap)="visitRestaurant()" height="87" width="80"></Image>
They are redirected to the restaurant.component.html page.
I defined the tap event as shown up there and then I have on my home.component.ts the following:
import { Router } from "#angular/router";
import { Component, OnInit } from "#angular/core";
#Component({
selector: "Home",
moduleId: module.id,
templateUrl: "./home.component.html",
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
constructor(private router: Router) {
}
visitRestaurant() {
this.router.navigate(["/restaurant"]);
}
ngOnInit(): void {
}
}
When I click it, it fails though with the error:
ERROR Error: Uncaught (in promise): Error: Cannot match any routes.
URL Segment: 'restaurant'
I thought about adding the route here and also into app-routing.module.ts but whenever I try I get cannot find name: RestaurantComponent. So I assume I need to export the component somewhere but not sure where or how.
Can you guys help me?
This is my app-routing-module.ts in case it's useful:
import { NgModule } from "#angular/core";
import { Routes } from "#angular/router";
import { NativeScriptRouterModule } from "nativescript-angular/router";
const routes: Routes = [
{ path: "", redirectTo: "/home", pathMatch: "full" },
{ path: "home", loadChildren: "./home/home.module#HomeModule" }
];
#NgModule({
imports: [NativeScriptRouterModule.forRoot(routes)],
exports: [NativeScriptRouterModule]
})
export class AppRoutingModule { }
Here's my restaurant.component.ts code:
import { Router } from "#angular/router";
import { Component, OnInit } from "#angular/core";
#Component({
selector: "Restaurant",
moduleId: module.id,
templateUrl: "./restaurant.component.html",
styleUrls: ['./restaurant.component.css']
})
export class RestaurantComponent implements OnInit {
constructor(private router: Router) {
}
ngOnInit(): void {
}
}
You need to add a route for /restaurant. For example, you might do:
const routes: Routes = [
{ path: "", redirectTo: "/home", pathMatch: "full" },
{ path: "home", loadChildren: "./home/home.module#HomeModule" },
{ path: "restaurant", component: RestaurantComponent }
];
Additionally, you'll want to make sure your export/import statements appear appropriately.
Within restaurant.component.ts:
#Component({ ... })
export class RestaurantComponent { ... }
Within app-routing.module.ts:
import { RestaurantComponent } from ' ... ';

Resources