delete header and footer with my page gestion-projet - angular8

I want to delete header, footer and preloader in my page gestion-projet i use location in my code but it not works i have error when i inject the id what is the good syntax?
app.component.html
<app-preloader *ngIf="!(location == '/auth'|| location=='/dashbord'|| location == '/gestion-employee'
|| location =='/update-projet/:id')"></app-preloader>
<app-header *ngIf="!(location == '/update-projet/:id' || location == '/coming-soon' || location ==
'/gestion-employee' || location == '/not-found' || location =='/auth' ||location=='/dashbord')">
</app-header>
<router-outlet></router-outlet>
<app-footer *ngIf="!(location == '/update-projet/:id' || location == '/coming-soon' || location ==
'/gestion-employee' || location == '/not-found' || location == '/auth'|| location=='/dashbord')">
</app-footer>

It would be better to do this kind of operations in ts file. It will be easy to debug and less work for angular when recompiling template.
Also consider following example
if (a != b || c != d)
If you want to take negation out as common then your || should have to convert to &&
Like
if (!( a == b && c == d))
I think you did mistake here.
And you can do this is ts like
showPreloader = !(location == '/auth' && location=='/dashbord' && location == '/gestion-employee') && location.indexOf('/update-projet/') > -1);
showHeaderFooter = !(location.indexOf('/update-projet/') > -1 && location == '/coming-soon' && location == '/gestion-employee' && location == '/not-found' && location =='/auth' && location=='/dashbord')
Then your template will become like this
<app-preloader *ngIf="showPreloader"></app-preloader>
<app-header *ngIf="showHeaderFooter"></app-header>
<router-outlet></router-outlet>
<app-footer *ngIf="showHeaderFooter"></app-footer>
Also make sure you are updating these booleans after every route change

my file app.component.ts
`
import { Component, OnInit, OnDestroy } from '#angular/core';
import { Router, NavigationStart, NavigationCancel, NavigationEnd }
from'#angular/router';
import { Location, LocationStrategy, PathLocationStrategy } from
'#angular/common';
import { filter } from 'rxjs/operators';
declare let $: any;
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss'],
providers: [
Location, {
provide: LocationStrategy,
useClass: PathLocationStrategy
}
]
})
export class AppComponent implements OnInit, OnDestroy {
location: any;
routerSubscription: any;
constructor(private router: Router) {
}
ngOnInit() {
this.recallJsFuntions();
}
recallJsFuntions() {
this.router.events
.subscribe((event) => {
if ( event instanceof NavigationStart ) {
$('.preloader').fadeIn('slow');
}
});
this.routerSubscription = this.router.events
.pipe(filter(event => event instanceof NavigationEnd || event instanceof NavigationCancel))
.subscribe(event => {
$.getScript('../assets/js/custom.js');
$('.preloader').fadeOut('slow');
this.location = this.router.url;
console.log(location);
if (!(event instanceof NavigationEnd)) {
return;
}
window.scrollTo(0, 0);
});
}
ngOnDestroy() {
this.routerSubscription.unsubscribe();
}
}
`

Related

Making a web component using Vue

I am currently working on web components and shadow DOM.
I can see that it is possible to create a native web component using Vue3 here
Vue docs. But I am currently facing issues building the native component file from vuejs files. I have googled for some time and found there are not many helpful content for it.
Building Web Components with Vue 3.2 is by far the most helpful blog I have found. Still I am unable to do production build of my files.
Currently I am getting 2 files after build.
import {
r as c,
c as l,
o as a,
a as u,
b as d,
d as f,
t as m,
u as p,
e as g,
} from "./vendor.21fe8919.js";
const y = function () {
const r = document.createElement("link").relList;
if (r && r.supports && r.supports("modulepreload")) return;
for (const e of document.querySelectorAll('link[rel="modulepreload"]')) o(e);
new MutationObserver((e) => {
for (const t of e)
if (t.type === "childList")
for (const s of t.addedNodes)
s.tagName === "LINK" && s.rel === "modulepreload" && o(s);
}).observe(document, { childList: !0, subtree: !0 });
function i(e) {
const t = {};
return (
e.integrity && (t.integrity = e.integrity),
e.referrerpolicy && (t.referrerPolicy = e.referrerpolicy),
e.crossorigin === "use-credentials"
? (t.credentials = "include")
: e.crossorigin === "anonymous"
? (t.credentials = "omit")
: (t.credentials = "same-origin"),
t
);
}
function o(e) {
if (e.ep) return;
e.ep = !0;
const t = i(e);
fetch(e.href, t);
}
};
y();
const h = {
props: { timeZone: { type: String, default: "America/Los_Angeles" } },
emits: ["datechange"],
setup(n, { emit: r }) {
const i = n,
o = c(new Date()),
e = l(() => o.value.toLocaleString("en-US", { timeZone: i.timeZone }));
return (
setInterval(() => {
(o.value = new Date()), r("datechange", e);
}, 1e3),
(t, s) => (
a(), u("div", null, [d(t.$slots, "prefix"), f(" " + m(p(e)), 1)])
)
);
},
},
v = g(h);
customElements.define("current-time", v);
document.querySelector("current-time").addEventListener("datechange", L);
function L(n) {
console.log(n.detail[0].value);
}
But i would like the build file to be in following format for my use case.
class CurrentTime extends HTMLElement {
connectedCallback() {
this.innerHTML = new Date();
setInterval(() => this.innerHTML = new Date(), 1000)
}
}
// Define it as a custom element
customElements.define('current-time', CurrentTime);
vite config file
import { defineConfig } from "vite";
import vue from "#vitejs/plugin-vue";
export default defineConfig({
plugins: [vue({ customElement: true })],
});

Value not overriding while set its value in loop in Vue JS and Firebase

I am getting data from firebase and overriding my roomName value in the loop. But outside the loop, it will not get the updated value.
Can someone please help me with the same?
export default {
name: "Chat",
components: {
ChatMessages
},
data(){
return{
rooms: [],
roomName: null,
}
},
mounted() {
this.getRooms();
},
methods: {
getRooms() {
roomsRef.orderByChild('name').once('value').then(snapshot => {
this.rooms = snapshot.val();
});
},
selectUser: function(userId) {
$.each(this.rooms,function(index,data){
if((data.sender_id == firebase.auth().currentUser.uid && data.receiver_id == userId ) || (data.sender_id == userId && data.receiver_id == firebase.auth().currentUser.uid )){
this.roomName = data.room_name;
}
});
if(this.roomName == null){
console.log("Null");
console.log(this.roomName);
}else{
console.log("Not Null");
console.log(this.roomName);
}
},
}
}
As pointed out by User 28 in the comment section, you need to use an arrow function:
$.each(this.rooms,(index,data) => {
if((data.sender_id == firebase.auth().currentUser.uid && data.receiver_id == userId ) || (data.sender_id == userId && data.receiver_id == firebase.auth().currentUser.uid )){
this.roomName = data.room_name;
}
});
Explanation. A "normal" function binds its own this. An arrow function inherits the this of the parent scope. Read more here: https://www.codementor.io/#dariogarciamoya/understanding-this-in-javascript-with-arrow-functions-gcpjwfyuc

integrate vue-i18n in vue-beautiful-chat

I try to integrate (vue-i18n) at this library (https://github.com/mattmezza/vue-beautiful-chat) in src folder but I have some integration problems
so,
in this file ./i18n/translations.js => we have the translations
in src/index.js
import Launcher from './Launcher.vue'
import VTooltip from 'v-tooltip'
import VueI18n from 'vue-i18n'
import messages from './i18n/translations.js'
const defaultComponentName = 'beautiful-chat'
const Plugin = {
install (Vue, options = {}) {
/**
* Makes sure that plugin can be installed only once
*/
if (this.installed) {
return
}
Vue.use(VueI18n)
const locale = navigator.language
const i18n = new VueI18n({
fallbackLocale: 'fr',
locale: locale,
messages
})
this.installed = true
this.event = new Vue({i18n})
this.dynamicContainer = null
this.componentName = options.componentName || defaultComponentName
/**
* Plugin API
*/
Vue.prototype.$chat = {
_setDynamicContainer (dynamicContainer) {
Plugin.dynamicContainer = dynamicContainer
}
}
/**
* Sets custom component name (if provided)
*/
Vue.component(this.componentName, Launcher)
Vue.use(VTooltip)
Vue.use(VueI18n)
}
}
export default Plugin
And i start to change in the file "src/Launcher.vue" "you" in the header of the chat
computed: {
chatWindowTitle() {
if (this.title !== '') {
return this.title
}
if (this.participants.length === 0) {
return $t('participant.you_only')
} else if (this.participants.length > 1) {
return $t('participant.you_and_participants', { participant: 'this.participants[0].name' })
} else {
return 'You & ' + this.participants[0].name
}
}
},
but i receive this error
i have try few others methods as this.$i18n and others.
Can you help me please ?
Thanks a lot.
Are you possible missing the "this" when referring to "$t" on the computed property?
computed: {
chatWindowTitle() {
if (this.title !== '') {
return this.title
}
if (this.participants.length === 0) {
return this.$t('participant.you_only')
} else if (this.participants.length > 1) {
return this.$t('participant.you_and_participants', { participant: 'this.participants[0].name' })
} else {
return 'You & ' + this.participants[0].name
}
}
},

Vuex loop array of objects and create conditional statement for key:value

i'm am attempting to pull in data through VueX and iterate over an array of objects to get the menu_code. I am successfully get the data i need but i need to show/hide a button according to these conditions:
if ALL of the data in menu_code is NULL, don't show the button.
if one or more of the menu_code data is !== NULL, show the button.
unsure if i'm linking the hasCode data correctly to the button.
// MenuPage.vue
<button v-show="hasMenuCode">hide me if no menu code</button>
<script lang="ts">
import {
Vue,
Component,
Watch,
Prop
} from 'vue-property-decorator';
import {
namespace
} from 'vuex-class';
import MenuItem from "../../models/menu/MenuItem";
export default class MenuPage extends Vue {
#namespace('menu').State('items') items!: MenuItem[];
hasCode = true;
hasMenuCode() {
for (let i = 0; i < this.items.length; i++) {
if (this.items[i].menu_code !== null) {
this.hasCode = true;
} else {
this.hasCode = false;
}
}
}
}
</script>
// MenuItem.ts
import AbstractModel from "../AbstractModel";
import Image from '../common/Image';
import MenuRelationship from "./common/MenuRelationship";
import Availability from "../common/Availability";
import Pricing from "../common/Pricing";
interface MenuItemMessages {
product_unavailable_message: string;
}
interface ItemOrderSettings {
min_qty: number;
max_qty: number;
}
export default class MenuItem extends AbstractModel {
name: string;
menu_code: string;
description: string;
image: Image;
has_user_restrictions: boolean;
availability: Availability;
pricing: Pricing;
ordering: ItemOrderSettings;
messages: MenuItemMessages;
prompts: MenuRelationship[];
setMenus: MenuRelationship[];
constructor(props: any) {
super(props);
this.name = props.name;
this.menu_code = props.menu_code;
this.description = props.description;
this.image = props.image;
this.has_user_restrictions = props.has_user_restrictions;
this.availability = new Availability(props.availability);
this.pricing = new Pricing(props.pricing);
this.ordering = props.ordering;
this.messages = props.messages;
this.prompts = props.prompts;
this.setMenus = props.setMenus;
}
}
Base on your requirement, you need to return if there is any item has menu_code, otherwise the loop continues and it only take the value of the final item in this.items
hasMenuCode() {
for (let i = 0; i < this.items.length; i++) {
if (this.items[i].menu_code !== null) {
this.hasCode = true;
return
} else {
this.hasCode = false;
}
}
}
Shorter implementation
hasMenuCode() {
return this.items.some(item => item.menu_code !== null)
}

Mithril redraw only 1 module

If I have like 10 m.module on my page, can I call m.startComputation, m.endComputation, m.redraw or m.request for only one of those modules?
It looks like any of these will redraw all of my modules.
I know only module 1 will be affected by some piece of code, I only want mithril to redraw that.
Right now, there's no simple support for multi-tenancy (i.e. running multiple modules independently of each other).
The workaround would involve using subtree directives to prevent redraws on other modules, e.g.
//helpers
var target
function tenant(id, module) {
return {
controller: module.controller,
view: function(ctrl) {
return target == id ? module.view(ctrl) : {subtree: "retain"}
}
}
}
function local(id, callback) {
return function(e) {
target = id
callback.call(this, e)
}
}
//a module
var MyModule = {
controller: function() {
this.doStuff = function() {alert(1)}
},
view: function() {
return m("button[type=button]", {
onclick: local("MyModule", ctrl.doStuff)
}, "redraw only MyModule")
}
}
//init
m.module(element, tenant("MyModule", MyModule))
You could probably also use something like this or this to automate decorating of event handlers w/ local
Need multi-tenancy support for components ? Here is my gist link
var z = (function (){
//helpers
var cache = {};
var target;
var type = {}.toString;
var tenant=function(componentName, component) {
return {
controller: component.controller,
view: function(ctrl) {
var args=[];
if (arguments.length > 1) args = args.concat([].slice.call(arguments, 1))
if((type.call(target) === '[object Array]' && target.indexOf(componentName) > -1) || target === componentName || target === "all")
return component.view.apply(component, args.length ? [ctrl].concat(args) : [ctrl])
else
return {subtree: "retain"}
}
}
}
return {
withTarget:function(components, callback) {
return function(e) {
target = components;
callback.call(this, e)
}
},
component:function(componentName,component){
//target = componentName;
var args=[];
if (arguments.length > 2) args = args.concat([].slice.call(arguments, 2))
return m.component.apply(undefined,[tenant(componentName,component)].concat(args));
},
setTarget:function(targets){
target = targets;
},
bindOnce:function(componentName,viewName,view) {
if(cache[componentName] === undefined) {
cache[componentName] = {};
}
if (cache[componentName][viewName] === undefined) {
cache[componentName][viewName] = true
return view()
}
else return {subtree: "retain"}
},
removeCache:function(componentName){
delete cache[componentName]
}
}
})();